Introduction to C / C++ Programming
File I/O

The Stream Class Hierarchy

The ifstream Class

        #include <fstream>
        if( fin.fail( ) ) {
            cerr << "Error - Failed to open " << filename << endl;
            exit( -1 );  // Or use a loop to ask for a different file name.
        }
        fin >> xMin;

The ofstream Class

        ofstream fout( "outputFile.txt" );
        fout << "The minimum oxygen percentage is " << minO2 << endl;

Reading Data Files

  1. Specified Number of Records
  2.         int nData;
            double x, y, z;
            
            fin >> nData;
            for( int i = 0; i < nData; i++ ) {
                fin >> x >> y >> z;
                // Do something with x, y, z
            } for loop reading input data
  3. Sentinel Value
  4.         double x, y;
            
            while( true ) {
                fin >> x >> y;
                if( x = = 0.0 && y = = 0.0 )
                    break;
                // Do something with x and y
            }  // while loop reading input data
  5. Detect End of File
  6.         double x, y, z;
            
            fin >> x >> y >> z;
            while ( !fin.eof( ) ) {
                // Do something with x, y, z
                
                // Read in the new data for the next loop iteration.
                fin >> x >> y >> z;
            } // while loop reading until the end of file

Error Checking Using the Stream State