I/O Constructors

Syntax:

    #include <fstream>
    fstream( const char *filename, ios_base::openmode mode );
    ifstream( const char *filename, ios_base::openmode mode );
    ofstream( const char *filename, ios_base::openmode mode );

The fstream, ifstream, and ofstream objects are used to do file I/O. The optional mode defines how the file is to be opened, according to the IO stream mode flags. The optional filename specifies the file to be opened and associated with the stream.

Input and output file streams can be used in a similar manner to C++ predefined I/O streams, cin and cout.

For example, the following code reads input data and appends the result to an output file.

    ifstream fin( "/tmp/data.txt" );
    ofstream fout( "/tmp/results.txt", ios_base::app );
    while ( fin >> temp )
      fout << temp + 2 << endl;
    // Files are closed automatically when the variables fin and fout fall out of scope.

Related Topics: close, open