C++ Error Handling During File Operation

Sometimes, during file operations, errors may also creep in. For example, a file being opened for reading might not exist. Alternatively, a file name used to create a new file may already exist. Alternatively, an attempt could be made to read past the end of the file. Or such an invalid operation may be performed. There might not be enough space on the disc for storing data.

C++ file streams inherit "stream-state" members from the ios class. These members store information on the status of a file that is currently being used and are used to check for errors like the ones described above and to ensure that processing goes smoothly. An integer that contains the following flags' encoding is used to store the current state of the I/O system. These flags are as follows:

Name Meaning
eofbit 1 when end-of-file is encountered, 0 otherwise.
failbit 1 when a non-fatal I/O error has occurred, 0 otherwise
badbit 1 when a fatal I/O error has occurred, 0 otherwise
goodbit 0 value

C++ Error Handling Functions

There are several error handling functions supported by class ios that help you read and process the status recorded in a file stream.

The following list describes these error handling functions and their meaning:

eof() returns true if eofbit is set, whereas bad() returns true if badbit is set. fail() returns true if the failbit is set, whereas good() returns true if there are no errors. If not, they return false.

These functions may be used at the appropriate points in a program to determine the status of a file stream and take the appropriate corrective action. For instance:

:
ifstream fin;
fin.open("master", ios::in);
while(!fin.fail())
{
   :                 // process the file
}
if(fin.eof())
{
   :                 // terminate the program
}
else if(fin.bad())
{
   :                 // report fatal error
}
else
{
   fin.clear();      // clear error-state flags
   :
}
:

C++ Error Handling Example

Here is an example program illustrating error handling during file operations in a C++ program:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
   string myline, myfile;
   char ch;
   cout << "Enter file name: ";
   getline(cin, myfile);
   ifstream ifs(myfile);
   if (ifs)
   {
      cout << "The entered file already exists. Please try again.\n";
      return 0;
   }
   else
   {
      ifs.close();
      ofstream ofs(myfile);
      if(ofs.fail())
      {
         cout << "Error occurred!\n";
         return 0;
      }
      cout << "Enter a line to store in the file: ";
      getline(cin, myline);
      ofs << myline << "\n";
      cout << "\nThe information you entered was successfully saved!\n";
      ofs.close();
      cout << "\nDo you want to read the file? (y/n): ";
      cin >> ch;
      if (ch == 'y' || ch == 'Y')
      {
         ifstream ifs(myfile);
         while (getline(ifs, myline))
            cout << myline;
         ifs.close();
      }
   }
   cout << endl;
   return 0;
}

The following snapshot shows the initial output produced by the above program:

C++ error handling

Now type the name of the file, say "myfile.txt," and hit the ENTER key to create a file with the given name in the current directory. The current directory is the directory where the C++ source code is saved. The following snapshot shows the sample output after providing the stated input:

c++ error handling program

Because no errors were displayed, the file was successfully created, and it now has a line to store in it.For example, if I type "Hello there" as a line of text and hit the ENTER key, here is the output:

error handling in c++ example

Now you can type "y" and hit the ENTER key to read the content of the file or anything else to skip or stop the execution of the program. The following sample run is given for your understanding.

error handling in C++ program

More Examples

Here are the list of some more C++ examples, that you can go for:

C++ Quiz


« Previous Tutorial Next Tutorial »