C++ Tutorial: File Handling in C++
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
Similarly, to read from file we open the file using constructor as
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
// some operation
Similarly for reading purpose