Opening and Closing a File
I think you'll find this interesting. You'll learn how to access disk files in the following sections. First of all you have to make use of another header file : fstream.h This header file has a number of classes already defined within it. Some of them are ofstream, ifstream, fstream etc...
To access a file you have to have a stream. Hence first we declare a stream. The stream will be an object of one of the classes in fstream.
ifstream in; // stream in created for input
ofstream out; // stream out created for output
fstream inout; // stream inout created for input and output
Once you've created a stream, you can use the open ( )function to associate it to a disk file. The open ( ) function is a member of all the three classes. It can be used as follows :
out.open("text.txt") ; // Opens a file called text.txt for output. The file is opened using the stream out which was created earlier.
Point to be noted : 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 (using ifstream), the data in the file can be displayed on the screen.
Suppose there was a file text.txt already. When using 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 :
ofstream out("text.txt"); // This creates an object out for output and opens the file text.txt.
This statement makes use of the constructor in the ofstream class. Ifstream and fstream also have the constructor.
Closing a File :
The member function for closing is close ( ). Since you do all I/O through the stream, you have to close the stream as follows:
out.close( ); // To close a stream - type the name of the stream followed by a dot and then close ( ).
Actually you can link this to the object and classes concept. Out is an object and close is a member function of the ofstream class. Hence by saying out.close( ); you're actually calling the member function.
In the next section we'll see : Can errors occur while opening a file?
or go back to Contents page 2.