Home Segments Index Top Previous Next

402: Mainline

Collecting what you have just learned about file input and output, you easily can amend programs that read from your keyboard and display on your screen such that they read from a file and write to a file.

The following program, for example, fills an array with cylinder radii and lengths from a file named test.data, and then writes the sum of the cylinders' volumes into a file named test.result:

#include 
#include
const double pi = 3.14159;
// Define the cylinder class:
class cylinder {
  public: double radius, length;
          double volume ( ) {return pi * radius * radius * length;}
};
// Define cylinder array:
cylinder oil_tanks[100];
main ( ) {
  // Declare various variables:
  int limit, counter;
  double sum = 0.0;
  // Connect an input stream to the file named test.data:     
  ifstream cylinder_stream ("test.data");                     
  // Connect an output stream to the file named test.result:  
  ofstream volume_stream ("test.result");                     
  // Read numbers from the test.data file: 
  for (limit = 0; 
       cylinder_stream >> oil_tanks[limit].radius 
                       >> oil_tanks[limit].length; 
       ++limit) 
    ; 
  // Compute volume: 
  for (counter = 0; counter < limit; ++counter) 
    sum = sum + oil_tanks[counter].volume ( ); 
  // Write sum into the test.result file: 
  volume_stream << "The total volume in the " 
                << limit << " storage tanks is " 
                << sum << endl; 
} 
--- Data ---
4.7       40.0 
3.5       35.5 
3.5       45.0       
--- Result --- 
The total volume in the 3 storage tanks is 5873.91 

Once you have finished writing information into a file, you must close the file before you can open it for reading and further processing. The do-nothing, somewhat dangerous way to close your files is to wait until your program stops executing: At that point, your operating system is supposed to close all open files automatically. The safer way to close your files is to include an explicit file-closing statement:

stream name.close ( ); 

The following, for example, closes the output-file stream named volume_stream:

volume_stream.close ( ); 

The notation reflects the fact that streams are actually class objects. Evidently, close is a member function of the output-file-stream class or a superclass of that class.