File handling
Stream:
Stream means flow of data.
Input stream means flow of data from file to program.
Output stream is the flow of data from program to file.
Stream Class Model:
§ ios: This is base class of
stream class hierarchy. istream class and ostream class are inherited from this
class.
§ istream: This class is
inherited from ios class. This class is useful for input stream. If we want to
read data from file to the program this class is used.
§ ostream: This class is
inherited from ios class. This class is useful for output stream. If we want to
write data to file from the program ostream class is used.
§ iostream: This class is
inherited from ostream class and istream class. It is work as a base class for
fstream class.
§ fstream: This class is
inherited from iostream class. This class is used to write and read from the
file.
§ ifstream: This class is used
to read data from the file.
§ istream_withassign: This class
is inherited from istream class. Cin is an object of istream_withassign class.
§ ofstream: This class is used
to write data to file.
§ ostream_withassign: This class
is inherited from ostream class. Cout is an object of ostream_withassign class.
Text output
Text output is possible with two options. 1.
Insertion operator 2. Put function
Insertion operator: It is used to write data from program to file.
void main()
{
char c=‘a’;
ofstream
of1(“test.dat”);
of1<<c;
}
Same way we can write data of integer, float or string type also.
Prototype of
put()
ostream
& ostream :: put(char c)
The put function is called through an object of ostream
,or an object of any subclass of ostream class.
void main()
{
char c=‘a’;
ofstream
of1(“test.dat”);
of1.put(c);
}
Text
input : There are three options for text input
§ Extraction operator
§ get()
§ getline()
Extraction operator
It is used to get input from file to the program
It is overloaded in istream class.
void main()
{
char c;
ifstream
if1(“test.dat”);
if1>>c;
cout<<c;
}
Extraction operator can work with int, float and
string also.
get() function
§ The get function is available
in istream class.
§ The get function read single
byte from the file and stores in character variable.
§ It is member of istream class
and can be invoked with istream class object or object of subclass of istream
class object.
§ The prototype of istream class
is:
istream & istream :: get(char &);
Example of get()
void main()
{
char c;
ifstream
if1(“test.dat”);
if1.get(c);
cout<<c;
}
getline() function