I/O Constructors

C/C++ Reference

I/O Constructors
Syntax:
  #include <fstream>
  fstream( const char *filename, openmode mode );
  ifstream( const char *filename, openmode mode );
  ofstream( const char *filename, 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.

Example code:

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::app );
  while( fin >> temp )
    fout << temp + 2 << endl;
  fin.close();
  fout.close();         
Related topics: