C++ Tutorial: File Handling in C++

Opening and Closing Files
In C++, a file is opened by either of two ways. First way is the constructor function of the file stream class and second way is by making use of member function open() of the same class. After using the file it must be closed. The file can also be closed by two ways. First way is automatically closing by the destructor of the file stream class and the second way is closing the file explicitly by the member function close() of the file stream class.
(A) Opening and Closing Files using Constructor and Destructor
For every action on file, it must be opened first. A file is opened in either read, write or append or other modes. Using constructor, a file can be opened by passing a filename as parameter in the constructor. Since constructor is invoked during the time of object creation, it can be used to initialize the file stream object with the filename, so that the file stream object refers to the file. The statement
ofstream oufile(“myfile.txt”);

opens the file myfile.txt for output. After opening the file through file stream object, the read/write operation can be performed through the stream operator insertion (<<) and extraction (>>). To write to the file “myfile.txt” opened through file stream object outfile we write the statement

outfile<<“John Doe”;

Similarly, to read from file we open the file using constructor as

ifstream infile(“myfile.txt”);

This statement reads data from file “myfile.txt” to variable age through file stream object infile.

(B) Opening and Closing Files Explicitly

Apart from constructor, file can be opened explicitly by making use of member function open(). The function open() is a member of all the file stream classes ofstream, ifstream and fstream. The syntax for opening and closing file explicitly for writing purpose is

ofstream fout;
// some operation

Similarly for reading purpose

ifstream fin;
//some operation

SHARE C++ Tutorial: File Handling in C++

You may also like...

Leave a Reply

Your email address will not be published.