Now we shall deal with file I/O and to access any device you have to make use of another header file: ‘fstream.h’. This header file has a number of classes already defined. To access a file you have to have a stream. We have already come across the classes istream, ostream and iostream. From these classes, 3 more classes are derived (they are ofstream, ifstream, and fstream) and these classes are specifically useful for streams used in ‘file’ operations. The hierarchy of classes will be as shown in the figure.
As can be seen, the ‘ifstream’, ‘ofstream’ and ‘fstream’ classes are derived from the ‘istream’, ‘ostream’ and ‘iostream’ classes. These are file streams that are derived from the general I/O streams that we have seen earlier.
ifstream in; // file stream named ‘in’ created for handling input
ofstream out; // file stream named ‘out’ created for handling output
fstream both; // file stream named ‘both’- can handle both input and output
Once you’ve created a stream, you can use the open ( ) function to associate it to a ‘file’. To associate the stream to a disk file, we should specify the name of the disk file. The open ( ) function is a member available in all the three classes. It can be used as follows:
out.open (“text.txt”) ; // Opens a file called text.txt for output.
Note: When you say that a file is opened for output, it actually means that now you can write data to the file. When a file is opened for input (i.e. using ifstream), the data in the file can be displayed on the screen.
What if there already is a file called text.txt. When using the output stream (ofstream), the stream will create a new file text.txt. Whatever content was there in the original text.txt gets deleted and you can write new data to text.txt.
The 3 classes (ofstream, ifstream, fstream) have a constructor function that makes it easier to open a file. Example:
This creates an object out for output and opens the file text.txt in one single statement. Here we don’t make use of the open ( ) function.
Closing a File
Anything that you open has to be closed. The member function for closing is close ( ). Since you do all I/O through the stream, you have to close the stream as follows:
Actually you can link this back to the object and classes concept. ‘stream-name’ is an object and close is a member function of the ofstream class. Hence by saying
You’re actually invoking the member function close( ). A stream is associated to a device when using the open function. When the close ( ) function is used, the stream is disassociated from the device.
Happy Coding 🙂