Subject:- Object Oriented Programming
UNIT-IV
Files and Streams
Department of Computer Engineering
Pimpri Chinchwad College of Engineering & Research,
Ravet, Pune
1
Files and Streams
● A C++ class is a collection of data and the methods necessary to control and maintain that data. such as stream classes.
● A class is a data type, analogous to ints, floats, and doubles. A C++ object is a specific variable having a class as its
data type. cin and cout are special pre-specified objects with different classes as their data types.
● A C++ stream is a flow of data into or out of a program, such as the data written to cout or read from cin.
● For this class we are currently interested in four different classes:
○ istream is a general purpose input stream. cin is an example of an istream.
○ ostream is a general purpose output stream. cout examples of ostreams.
○ ifstream is an input file stream. It is a special kind of an istream that reads in data from a data file.
○ ofstream is an output file stream. It is a special kind of ostream that writes data out to a data file.
Stream
• We give input to the executing program and the execution program gives back the
output.
• The sequence of bytes given as input to the executing program and the sequence of
bytes that comes as output from the executing program are called stream.
• In other words, streams are nothing but the flow of data in a sequence.
• The input and output operation between the executing program and the devices
like keyboard and monitor are known as “console I/O operation”.
• The input and output operation between the executing program and files are
known as “disk I/O operation”.
Files and Streams
● Object Oriented Programming makes heavy use of a concept called inheritance, in
which some classes inherit the properties of previously written classes.
● The descendant classes then add on additional properties, making them specializations of
their parent class.
● For example, we see that ifstream is a specialization of istream.
● An ifstream IS an istream, and includes all the properties of the istream class, plus some
additional properties of its own.
The Stream Class Hierarchy
The ifstream Class
● An ifstream is an input file stream, i.e. a stream of data used for reading input from a
file.
● Because an ifstream IS an istream, anything you can do to an istream you can also do the
same way to an ifstream.
○ In particular, cin is an example of an istream, so anything that you can do with cin
you can also do with any ifstream.
● The use of ifstreams ( and ofstreams ) requires the inclusion of the fstream header:
#include <fstream>
The ifstream Class
Before you can use an ifstream, however, you must create a object of type ifstream and
connect it to a particular input file.
● This can be done in a single step, such as:
ifstream fin( "inputFile.txt" );
Here fin is a object of class ifstream.
● Or you can create the ifstream objectand open the file in separate steps:
ifstream fin;
fin.open( "inputFile.txt" );
The ifstream Class
● Before you use a newly opened file, you should always check to make sure the file
opened properly. Every stream object has a fail( ) method that returns "true" if the stream
is in a failed state, or "false" otherwise:
if( fin.fail( ) )
{
cerr << "Error - Failed to open " << filename << endl;
exit( -1 ); // Or use a loop to ask for a different file name.
}
● Once you have created an ifstream and connected it to an open file, you read data out of
the file the same way that you read from cin:
fin >> xMin;
The ifstream Class
After you are completely done using a stream,you should always close it to prevent possible
corruption.
● This is especially true for output files, i.e. ofstreams.
fin.close( );
● After you have closed a stream, you can re-open it connected to a different file if you wish.
( I.e. you can reuse the stream variable.)
• For achieving file handling we need to follow the following steps:-
STEP 1-Naming a file
STEP 2-Opening a file
STEP 3-Writing data into the file
STEP 4-Reading data from the file
STEP 5-Closing a file.
C++ program to create a file
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream file; //object of fstream class
//opening file "sample.txt" in out(write) mode
file.open("sample.txt",ios::out);
if(!file)
{
cout<<"Error in creating file!!!";
return 0;
}
cout<<"File created successfully.";
//closing the file
file.close();
return 0;
}
Program for writing content on file
• #include<iostream>
• #include<fstream>
• using namespace std;
• int main()
• {
• int rno,fee;
• char name[50];
• ofstream fout("student.doc"); // File Created or open
• cout<<"Enter Data";
• cin>>rno>>name>>fee; //Read from Console( KB)
• fout<<rno<<name<<fee; fout.close(); // Write on File
• cout<<endl<<rno<<"\t"<<name<<"\t"<<fee; // display on console (screen)
• return 0;
• }
Read Write Operation on File
• #include<iostream>
• #include<fstream>
• using namespace std;
• int main()
• {
• int rno,fee;
• char name[50];
• ofstream fout("student.doc"); // File Created or open
• cout<<"Enter Data";
• cin>>rno>>name>>fee;
• fout<<rno<<name<<fee; // Write on File
• fout.close();
• cout<<endl<<rno<<"\t"<<name<<"\t"<<fee; // display on console (screen)
• ifstream fin ("student.doc"); // now read data in temporary variable
• fin>> rno>>name>>fee; // Read from file
• cout<<endl<<rno<<"\t"<<name<<"\t"<<fee;
• return 0;
• }
C++ program to read the text file
#include<iostream> //read and print file content
#include<fstream> while (!file.eof())
using namespace std; {
int main() file >> noskipws >> ch;
{
//reading from file
char ch;
const char *fileName="test.txt"; cout << ch; //printing
}
//declare object //close the file
ifstream file; file.close();
//open file
return 0;
file.open(fileName,ios::in);
if(!file) }
{
cout<<"Error in opening file!!!"<<endl;
return -1; //return from main
}
C++ program to write and read text in/from file
#include <iostream> //again open file in read mode
#include <fstream> file.open("sample.txt",ios::in);
using namespace std;
if(!file)
int main() {
{ cout<<"Error in opening file!!!"<<endl;
fstream file; //object of fstream class return 0;
}
//opening file "sample.txt" in out(write) mode
file.open("sample.txt",ios::out); //read untill end of file is not found.
char ch; //to read single character
if(!file) cout<<"File content: ";
{
cout<<"Error in creating file!!!"<<endl; while(!file.eof())
return 0; {
} file>>ch; //read single character from file
cout<<ch; // read content display on screen
cout<<"File created successfully."<<endl; }
//write text into file
file<<"ABCD."; file.close(); //close file
//closing the file
file.close(); return 0;
}
Ofstream Class
● An ofstream is an output file stream, and works exactly like ifstreams, except for output
instead of input.
● Once an ofstream is created, opened, and checked for no failures, you use it just like
cout:
ofstream fout( "outputFile.txt" );
fout << "The minimum oxygen percentage is " << minO2 << endl;
Ofstream Class
2. Another commonly used method is to look for a special value ( combination ) as a trigger to stop reading
data:
double x, y;
while( true )
fin >> x >> y;
if( x = = 0.0 && y = = 0.0 )
break;
// Do something with x and y
} // while loop reading input data
○ The difficulty with this method is that the sentinel value must be carefully chosen so as not to be
possible as valid data.
Ofstream Class
3. Detect End of File
i. If you know that the data you are reading goes all the way to the end of the file ( i.e.
there is no other data in the file after the data you are reading ), then you can just keep
on reading data until you detect that the end of the file has been reached.
ii. All istreams ( and ifstreams ) have a method, eof( ), that returns a boolean value of
true AFTER an attempt has been made to read past the end of the file, and false
otherwise.
iii. Because the true value isn't set until AFTER you have gone too far, it is important to:
(1) read some data first, then (2) check to see if you've gone past the end of the file,
and finally (3) use the data only after you have verified that the reading succeeded.
Note carefully in the following code that the check for the end of file always occurs
AFTER reading the data and BEFORE using the data that was read:
Ofstream Class
double x, y, z;
fin >> x >> y >> z;
while ( !fin.eof( ) ) {
// Do something with x, y, z
// Read in the new data for the next loop iteration.
fin >> x >> y >> z;
} // while loop reading until the end of file
File Mode Parameters
Each one of the open() member functions of the classes ofstream,
ifstream and fstream has a default mode that is used if the file is opened
without a second argument:
class default mode parameter
ofstream ios::out
ifstream ios::in
fstream ios::in | ios::out
File Mode Parameters
ios::in Open for input operations.
ios::out Open for output operations
ios::binary Open in binary mode.
ios::ate Set the initial position at the end of the file.
If this flag is not set to any value, the initial position is the beginning of the file.
ios::app All output operations are performed at the end of the file, appending the content to
the current content of the file. This flag can only be used in streams open for output-
only operations.
ios::trunc If the file opened for output operations already existed before, its previous content is
deleted and replaced by the new one.
File Mode Parameters
All these flags can be combined using the bitwise operator OR (|). For example, if we want to
open the file example.bin in binary mode to add data we could do it by the following call to
member function open():
1
2
ofstream myfile;
myfile.open ("example.bin", ios::out | ios::app | ios::binary);
File Pointers
In C++, we have a get pointer and put pointer for getting (Reading) data from a file and putting
data on a file (Writing) respectively.
● seekg :- seekg is used to get the pointer to desired location with respect to reference point.
Syntax:- filepointer.seekg(number of bytes, reference points);
Ex. fin.seekg(10,ios::beg);
Ex. 2
Input : "Hello World"
myFile.seekg(6, ios::beg);
Output : World
● tellg :- tellg is used to get to know where the get pointer is in the file.
● Syntax:- filepointer.tellg();
Ex. int pos= fin.tellg();
File Pointers
● seekp:- seekp is used to move the put pointer to desired location with respect to reference point
Syntax:- filepointer.seekp(number of bytes,reference points);
Ex. fout.seekp(10,ios::beg);
● tellp :- tellp is used to get to know where the put pointer is in the file.
Syntax:- filepointer.tellp();
Ex. int pos= fin.tellp();
C++ Error Handling during File Operation
Sometimes during file operations, errors may also creep in.
For example, a file being opened for reading might not exist. Or a file name used for a new file may already
exist. Or an attempt could be made to read past the end-of-file.
Or such as invalid operation may be performed. There might not be enough space in the disk for storing data.
To check for such errors and to ensure smooth processing, C++ file streams inherit 'stream-state' members from the
ios class that store the information on the status of a file that is being currently used. The current state of the I/O
system is held in an integer, in which the following flags are encoded :
C++ Error Handling during File Operation
Name Meaning
eofbit 1 when end-of-file is encountered, 0 otherwise.
failbit 1 when a non-fatal I/O error has occurred, 0 otherwise
badbit 1 when a fatal I/O error has occurred, 0 otherwise
goodbit 0 value
C++ Error Handling Functions
There are several error handling functions supported by class ios that help you read and process the
status recorded in a file stream.
Following table lists these error handling functions and their meaning :
Function Meaning
int bad() Returns a non-zero value if an invalid operation is attempted or any unrecoverable error has occurred. However, if it is
zero (false value), it may be possible to recover from any other error reported and continue operations.
int eof() Returns non-zero (true value) if end-of-file is encountered while reading; otherwise returns zero (false value).
int fail() Returns non-zero (true) when an input or output operation has failed.
int good() Returns non-zero (true) if no error has occurred. This means, all the above functions are false. For example, if fin.good() is
true, everything is okay with the stream named as fin and we can proceed to perform I/O operations. When it returns zero,
no further operations can be carried out.
clear() Resets the error state so that further operations can be attempted.
C++ Error Handling Functions
The above functions can be summarized as eof() returns true if eofbit is set; bad() returns true if badbit
is set. The fail() function returns true if failbit is set; the good() returns true there are no errors.
Otherwise, they return false.
These functions may be used in the appropriate places in a program to locate the status of a file stream
and thereby take the necessary corrective measures.
C++ Error Handling Functions
ifstream fin;
fin.open("master", ios::in);
while(!fin.fail())
{
: // process the file
}
if(fin.eof())
{
: // terminate the program
}
else if(fin.bad())
{
: // report fatal error
}
else
{
fin.clear(); // clear error-state flags
:
}
Overloading stream insertion (<<) and extraction (>>) operators in C++
C++ is able to input and output the built-in data types using the stream extraction
operator >> and the stream insertion operator <<.
The stream insertion and stream extraction operators also can be overloaded to
perform input and output for user-defined types like an object.
Here, it is important to make operator overloading function a friend of the class
because it would be called without creating an object.
Following example explains how extraction operator >> and insertion operator <<.
Program to Overloading stream insertion (<<) and extraction (>>) operators in C++
#include <iostream>
int main()
using namespace std;
{
class Distance
{ private: int feet; // 0 to infinite Distance D1(11, 10), D2(5, 11), D3;
int inches; // 0 to 12 cout << "Enter the value of object : " <<
public: // required constructors endl;
Distance() cin >> D3;
{ feet = 0; inches = 0; cout << "First Distance : " << D1 << endl;
} cout << "Second Distance :" << D2 << endl;
Distance(int f, int i) cout << "Third Distance :" << D3 << endl;
{ feet = f; inches = i; } return 0;
// overloading operator << }
friend ostream &operator<<( ostream &output, const Distance &D)
{
output << "F : " << D.feet << " I : " << D.inches;
return output;
}
// overloading operator >> OUTPUT:
Enter the value of object : 70 10
friend istream &operator>>( istream &input, Distance &D )
First Distance : F : 11 I : 10
{ Second Distance :F : 5 I : 11
input >> D.feet >> D.inches; return input; Third Distance :F : 70 I : 10
}
}; // class close
C++ Command Line Arguments
The most important function of C/C++ is main() function. It is mostly defined with a return type of int
and without parameters int main() { /* ... */ }
We can also give command-line arguments in C and C++. Command-line arguments are given after
the name of the program in command-line shell of Operating Systems.
To pass command line arguments, we typically define main() with two arguments : first argument is
the number of command line arguments and second is list of command-line arguments.
int main(int argc, char *argv[]) { /* ... */ }
C++ Command Line Arguments
● argc (ARGument Count) is int and stores number of command-line arguments passed by
the user including the name of the program. So if we pass a value to a program, value of argc
would be 2 (one for argument and one for program name)
● The value of argc should be non negative.
● argv(ARGument Vector) is array of character pointers listing all the arguments.
● If argc is greater than zero,the array elements from argv[0] to argv[argc-1] will contain
pointers to strings.
● argv[0] is the name of the program , After that till argv[argc-1] every element is command -
line arguments.
Steps to Execute Command line program in Ubuntu are
as follows:
Step 1: Type Program
Step 2: Save Program
Step 3: Complie Program
g++ -0 myprogram xyz.cpp
Step 4: Run Program
./ myprogram first_arg secon_arg third_arg....
// C++ program to demonstrate the use of
command line // arguments
#include <iostream>
using namespace std;
int main(int argc, char* argv[])
{
cout << "You have entered " << argc << " arguments:" << endl; // Using
a while loop to iterate through arguments
int i = 0;
while (i < argc)
{ cout << "Argument " << i << ": " << argv[i] << endl;
i++; }
return 0; }
comp@comp-V50t-Gen-2-13IOB:~$ g++ -o myprogram s.cpp
INPUT:
comp@comp-V50t-Gen-2-13IOB:~$ ./myprogram visit to libbrary
OUTPUT:
You have entered 4 arguments:
Argument 0: ./myprogram
Argument 1: visit
Argument 2: to
Argument 3: libbrary
Printer OUTPUT
It will possible to use console based program to send data to printer.
Many special filenames for hardware devices are defined by OS.
Which makes it possible to treat device like files.
-Some hardware device names are follows
•Con: it is for console
•Aur: first serial port
•Com2: second serial port
•lpt1: first parallel printer
•lpt2: second parallel printer
•lpt3: third parallel printer
•nul: used as dummy device
•Generally printer is connected to first parallel port of the system.
•So it is recommended to use lpt1 as file name to print through printer.
Program to send output to the Printer
#include <iostream>
include <fstream>
using namespace std;
int main()
{cout<<"Printing output using printer";
ofstream print("LPT1");
if(!print)
{cout<<"\n no printer connected";
return 1;
}
OUTPUT:
print<<"\n this is first line printed"; this is first line printed
print<<"\n Number:"<<1234; Number:1234 Float:82.94
print<<"\n Float:"<<82.94; char:A
print<<"\n char:"<<"A";
// Close the File
print.close();
return 0;}