Department of Engineering

IT Services

Files

Files are used for permanent retention of large amounts of data. To perform file processing in C++ the header file <fstream> must be included. The latter includes the definitions of the ifstream and ofstream classes. These are used for input from a file and output to a file. This is a more general form of the mechanisms described in section 11, allowing named files and different types.

The following statements open the file called input_data, and read in data which is stored sequentially in variables a, b and c:

   ifstream fin;
   fin.open("input_data");
   if (fin.good())
      fin >> a >> b >> c;
   else
   {
      // error opening file
   }

In a similar way data can be written (in this example, the values of an array) to a file called my_results with:

   ofstream fout;
   fout.open("my_results");
   if (fout.good())
   {
      for(int i=0; i<N; i++)
      {
         fout << array[i] << endl;
      }
   }
   else
   {
      // error opening file
   }

Note that fin and fout are arbitrary names chosen by the programmer. The good() member function of ifstream and ofstream objects returns false if there is an error.

After finishing reading from and writing to files they must be closed with the statements:

   fin.close();
   fout.close();

and the two variables fin and fout can be re-used for other files.