Return to Topic Menu | Computer Science Main Page | MathBits.com | Terms of Use | Resource CD

Methods of Detecting Errors when Accessing Files

If a program dealing with file access is not working properly, it is often hard to determine if the problem is within the program or if the problem is with the file access. 

Below are various methods of determining if your files have been accessed properly.
  These are program fragments -- not all code is included.

 

Example 1:

//model for error detection
//using header <assert.h>

#include <fstream.h>
#include <assert.h>

int main(void)
{
          . . .
          ofstream fout;
         
. . .
          fout.open("myFile");
          assert (! fout.fail( ));

              <send data to file>

          fout.close( );
          assert (! fout.fail( )):
         
. . . 
}

 

When using <assert.h>, if a problem with the file occurs, the error message will be:

Assertion failed....
Abnormal program termination.

In Example 1, the stream operation mode was not included.

Example 2:

//model for error detection using
//build your own error trap


#include <fstream.h>

int main(void)
{
     int num;
     ofstream.fout;
     fout.open("myFile";ios::out);
     if (fout)    
     {
           for(int i = 0; i < 10; i++)
           {
                 cin>>num:
                 fout<<num<<endl;
            }
     }
     else
     {
        cout<<"file not found.";
      }
      fout.close( );
      return 0;
}      

fout will be 0 (false) if an error exists.

In Example 2, the stream operation mode WAS included.

The file was formed using endl to organize the data in the file.

 

Example 3: 

//model for error detection similar
//to Example 2.
//file is filled with 10 numbers (1-10)
//separate numbers with whitespace

#include <fstream.h>
int main(void)
{
     int num;
     ofstream fout;
     fout.open("myFile", ios::out);
     if (! fout)
         cout<<"Error opening file.";
     else
     {
          for(int i = 1; i < 11; i++)
               fout<<i<<" ";
     }
     fout.close( );
     return 0;
}

 In Example 3, whitespace (" ") is used to organize the file.

 

Example 4:
//model for error detection with exit( )
//file is filled with apstrings
#include<iostream.h>
#include<fstream.h>
#include<stdlib.h>          //for exit()
#include "apstring.cpp"
int main(void)
{
     ofstream fout;
     apstring sentences, sent;
     fout.open("sentences.dat");
     if (! fout)       //using exit( ) for errors
     {
        cerr<<"Unable to open file"    
               <<endl;
        exit(1);
     }

     for(int i = 0; i < 5; i++)
     fout<<"This is sentence #" <<i+1 
           <<endl;
     fout.close( );
     return 0;
}