next up previous
Next: About this document ... Up: iomethods Previous: Formatting with ANSI C

Reading and Writing to a File

The simplest way to read from or write to a file is to write your code with cin and cout and use redirection. Suppose you wanted to do both at the same time. If your program is called myprog and you would like to take input from infile and write output to outfile, you would run it like this:

  myprog < infile > outfile
But this design works only if you have only one standard input or output stream. Suppose you write a program that needs values from a table in a file called tabledata and also requires prompting the user for some parameters. Logically there are then two input streams.

The solution is to use the class ifstream, which is derived from the class istream, so has many of its methods. The extra f reminds us that it deals with a file instead of stdin. The class ofstream is used for output to a file. Both of these classes are defined in the standard header fstream.

Here are the steps required for handling a file for either input or output:

  1. Create an instance of ifstream or ofstream.
  2. Open the file. (Check for failure to open.)
  3. Read from the file or write to it.
  4. Close the file.
Here is an example for input. A similar approach works for output.
  #include <fstream>
  int main(){
     ifstream table;                            // 1. Create instance
     float a[10];
     table.open("tabledata");                   // 2. Open the file
     if(table.bad()){                           //    Check open
       cerr << "Can't open tabledata\n";
       return 1;
     }
     for(int i = 0; i < 10; i++)table >> a[i];  // 3. Read data
     table.close();                             // 4. Close the file
     ...
  }
The name of the class instance table can be whatever we want. We would create a new instance of the class for each file we wanted to read. Notice that we use it with >> just like cin. The class method open takes the name of the file as its character string argument. That argument can also be a character array containing the name of the file to be opened. The class method close closes the file. While closing the file is not absolutely required, it is a good habit, since there is a (usually generous) upper limit to the number of files that can be kept open at once. As can be guessed from the example, the method bad checks whether the open operation succeeded. It could fail if the file wasn't there, for example.

It is possible to combine steps 1 and 2 using the constructor

  ifstream table("tabledata");

The methods eof and fail work for the ifstream class.


next up previous
Next: About this document ... Up: iomethods Previous: Formatting with ANSI C
Carleton DeTar 2007-10-31