Error Handling During File Operations

By
Last updated:

For instance, one of the following things may happen when dealing with the files

  • A file which we are attempting to open to reading does not exist.
  • The file name used or a new file may already exist.
  • We may attempt an invalid operation such as reading past the end of file.
  • There may not be any space in the disk for storing more data.
  • We may use an invalid filename.
  • We may attempt to perform an operation when the file is not opened for that purpose.

The class ios supports several member functions that can be used to read the status recorded in a file stream.

Function

eof ( ) – Returns true if end-of-file is encountered while reading otherwise returns false.

fail ( ) – Returns true when an input or output operation has failed.

bad ( ) – Returns true if an invalid operation is attempted or any unrecoverable error has occurred. However if it is false, it may be possible to recover from any error reported and continue operation.

good ( ) – Returns true if no error has occurred. This means, all the above functions are false. For instance if file.good ( ) is true, all is well with the stream file and we can proceed to perform input/output operations. When it returns false, nofurther operations can be carried out.

---
---
ifstream infile;
infile.open("ABC")
while(infile.fail)
{
---
--- (Process the file)
---
}
if(infile.bad())
{
--- (report fatal error)
}
else
{
infile.clear(); //Clear error (resets the error state
--- that further operation
--- can be attempted)
Read More Topics
Pure virtual function
Virtual base class
Operator overloading in C++
Class template with overload operators

Santhakumar Raja

Hello The goal of this blog is to keep students informed about developments in the field of education. encourages pupils to improve as writers and readers.

For Feedback - techactive6@gmail.com

Leave a Comment