H.A.14.1 - opening files (new)

OPENING TEXT FILES

 

 

       In C++, if the file open command is unsuccessful, the program continues to execute with no input data.  This will lead to a very misleading run-time error.  The first inclination is to assume that something is wrong with the code, when in fact, the program could not find the file on the hard disk.  We want to build in a check for correct file opening and halt the program if the file was not successfully opened.

 

       The following program will demonstrate a good file opening algorithm.  This program uses some tools which need explanation.

 

a.     The header file #include <stdlib.h> contain the abort() function which causes a program to halt.

b.    The function fail() examines the state of a file stream and determines the status of that file stream.  If something was unsuccessful, fail() returns true.

 

       This algorithm will need to use the explicit open command.  This requires the two-line approach described in the student outline in Section C.1.

 

       We will also use an apstring to store the file name and then convert the apstring into a C-style string.  The open command requires the use of a C-style string.

 

       Here is the algorithm.

 

Version 1

 

#include <iostream.h>

#include <fstream.h>

#include <apstring.h> 

#include <stdlib.h>                       // for abort()

 

main ()

{

         apstring  fn ("c:\\tcwin45\\ap98\\numbers.txt");

         ifstream  inFile;

 

         inFile.open (fn.c_str());  // convert apstring to C-style string, then open

         if (inFile.fail())

         {

                 cerr << fn << "did not open correctly" << endl;

                 abort();

         }

 

         ...  rest of code ...

         return 0;

}


 

       We could also prompt the user to input the file name.  A preference would be to code the file path into the source code as they are usually rather long, but some might prefer the flexibility of typing in the file path/name at runtime.

 

Version 2

 

main ()

{

         apstring  fn;

         ifstream  inFile;

 

         cout << "Enter file name to read";

         cin >> fn;

         inFile.open (fn.c_str());  // convert apstring to C-style string, then open

         if (inFile.fail())

         {

                 cerr << fn << "did not open correctly" << endl;

                 abort();

         }

         ... rest of code ...

}

 

 

       Either version helps to debug the file opening portion of programs.  This will save time in tracking down errors in programs.