Loading....
Coupon Accepted Successfully!

 

Error Handling Functions

Until now, we have performed the file operation without any knowledge of the failure or success of the function open() that opens the file. There are many reasons; they may result in errors during read/write operations of the program.
  1. An attempt to read a file that does not exist
  2. The file name specified for opening a new file may already exist
  3. An attempt to read the contents of a file when the file pointer is at the end of the file
  4. Insufficient disk space
  5. Invalid file name specified by the programmer
  6. An effort to write data to the file that is opened in the read-only mode
  7. A file opened may be already opened by another program
  8. An attempt to open the read-only file for writing operation
  9. Device error
The stream state member from the class ios receives values from the status bit of the active file. The class ios also contains many different member functions. These functions read the status bit of the file where an error occurred during program execution are stored. These functions are depicted in Table, and various status bits are described in Table.
 
All streams such as ofstream, ifstream, and fstream contain the state connected with them. Faults and illegal conditions are managed (controlled) by setting and checking the state properly. Figure describes it more clearly.
 
Fig: Status bits
Table: Status Bits

eofbit

End of file encountered.

0x01

failbit

Operation unsuccessful

0x02

badbit

Illegal operation due to wrong size of buffer

0x04

hardfail

Critical error

0x08

 
Table: Error trapping functions
 

Functions

Working and return value

fail()

Returns non-zero value if an operation is unsuccessful. This is carried out by reading the bits ios::failbit, ios:: badbit, and ios::hardfail of ios::state.

eof()

Returns non-zero value when the end of the file is detected; otherwise, it returns zero. The ios::eofbit is checked.

bad()

Returns non-zero value when an error is found in the operation. The ios::badbit is checked.

good()

Returns non-zero value if no error occurred during the file operation, that is, no status bits were set. This also indicates that the above functions are false. When this function returns true, we can proceed with the file operation.

rdstate()

Returns the stream state. It returns the value of various bits of the ios::state.

 
The following examples illustrate the techniques of error checking:
  1. An attempt to open a non-existent file for reading

ifstream in(data.txt”);

if (!in){ cout<< File not found”; }

  1. In the above format, an attempt is made to open a file for reading. If the file already exists, it will be opened; otherwise, the operation fails. Thus, by checking the value of the object in, we can confirm the failure or success of the operation and according to this, further processing can be decided.
  2. An attempt to open a read-only file for writing

ofstream out(data.txt”);

if (!out)

cout<<Unable to open file”;

else

cout<<“File opened”;

  1. Suppose the data.txt file is protected (marked read only) or used by another application in a multitasking operating environment. If the same file is opened in the write mode as shown above, the operation fails. By checking the value of the object out with the if() statement, we can catch the error and transfer the program control to a suitable sub-routine.
  2. Checking end of file

ifstream in(data.txt”);

while (!in.eof())

{

// read data from file

// display on screen

}

  1. We may seek to open an existing file and read its contents. After opening a file in the read mode, it is necessary to read the characters from the file using an appropriate function (read() or get()). While reading a file, the get pointer is advanced to the successive characters, and the same process can be repeated using loops. The compiler cannot determine the end of the file. The eof() function determines the end of the file. Thus, by checking the value of the eof() function, we can determine the end of the file. In addition, by checking the value of the object, the end of the file is determined. Such conditions should be placed in the while loop parentheses. While reading the file, use only while or for loop.
  2. Illegal file name

ifstream in(“*+**”);

while (!in.eof())

{

// read data from file

// display on screen

}

  1. While performing a file operation, it is the user’s responsibility to specify the correct file name. If an illegal file name is specified by the user, the file operation fails. In the above format, “*+**” is given as a file name that is invalid.
  2. Operation with unopened file

ifstream in(“DATA”);

while (!in.eof())

{

// read data from file

// display on screen

}

 
Suppose the “DATA” file does not exist and an attempt is made to open it for reading. Any operation applied with this file will be of no use. Hence, while performing a file operation, first we have to check whether the file is successfully opened or not. After the confirmation, we can proceed to the next step.
 
Programs referred to in the above discussion are explained below.
 

16.20 Write a program to detect whether the file is opened successfully or not.

#include<fstream.h>

#include<constream.h>

#include<string.h>

ifstream in; // Global object

void main()

{

clrscr();

void show (void);

in.open(“dat”) ;

char c;

if (in!=0) show();

else

cout<<“\n File not found”;

}

void show()

{

char c;

cout<<“\n Contents of file:”;

while (in)

{

in.get(c);

cout<<c;

}

}

OUTPUT
File not found
 
Explanation: In the above program, the object in of the ifstream class is declared globally. It can be accessed by any normal function. In the main() function, in is the object used for opening the file. If the open() function fails to open the file, it returns a zero; otherwise, it returns a non-zero value. The if statement checks the value of the object in, and if it is a non-zero show() function, it is invoked; otherwise, “File not found” message is displayed. The show() function reads the file and displays the contents on the screen. In the above program, the open()function tries to open “dat” file, which does not exist. Hence, the output is “File not found.” If the specified file exists, the contents of the file will be displayed.
 

16.21 Write a program to display status of various errors trapping functions.

#include<fstream.h>

#include<conio.h>

void main()

{

clrscr();

ifstream in;

in.open (“text.txt”, ios::nocreate);

if (!in)

cout<<“\n File not found”;

else

cout<<“\nFile=”<<in;

cout<<“\nError state=”<<in.rdstate();

cout<<“\ngood()=”<<in.good();

cout<<“\neof()=”<<in.eof();

cout<<“\nfail()=”<<in.fail();

cout<<“\nbad()=”<<in.bad();

in.close();

}

OUTPUT
File not found
Error state = 4
good() = 0
eof() = 0
fail() = 4
bad() = 4
 
Explanation: In the above program, an attempt is made to open a non-existent file. The if statement checks the value of the object in. The specified file does not exist; hence, it displays the message “File not found.” The program also displays the values of various bits using the functionsgood(), eof(), bad(), fail(), and rdstate() error trapping functions. For more information about these functions, please refer Table.




Test Your Skills Now!
Take a Quiz now
Reviewer Name