Professional Documents
Culture Documents
Sometimes during file operations, errors may also creep in. For example, a file being opened for reading
might not exist. Or a file name used for a new file may already exist. Or an attempt could be made to read
past the end-of-file. Or such as invalid operation may be performed. There might not be enough space in
the disk for storing data.
To check for such errors and to ensure smooth processing, C++ file streams inherit 'stream-state' members
from the ios class that store the information on the status of a file that is being currently used.
Every stream has four bits that keep track of the current state of the stream:
The eofbit is set to true when an attempt is made to read past the end of the file.
The badbit is set when corrupted data is read, i.e. when the type of data in the file does not match
the type being read.
The failbit is set when a file fails to open, or when the end of file is read, or when corrupted data
is read.
The goodbit is set to true whenever the other three bits are all false, and is false otherwise.
There are several error handling functions supported by class ios that help you read and process the status
recorded in a file stream.
Following table lists these error handling functions and their meaning :
Function Meaning
int fail() Returns non-zero (true) when an input or output operation has failed.
Returns non-zero (true) if no error has occurred. This means, all the above functions are
false. For example, if fin.good() is true, everything is okay with the stream named as fin
int good()
and we can proceed to perform I/O operations. When it returns zero, no further
operations can be carried out.
clear() Resets the error state so that further operations can be attempted
Code for ERROR HANDLING IN FILE OPERATIONS using clear() and
fail() function
Output:
In the above example, myfile is open for input operations, but we perform an output operation on
it, so failbit is set. The example calls then clear in order to remove the flag and allow further
operations like getline to be attempted on myfile.
Output:
Returns true if the eofbit error state flag is set for the stream.This flag is set by all standard input
operations when the End-of-File is reached in the sequence associated with the stream.
Note that the value returned by this function depends on the last operation performed on the
stream (and not on the next).Operations that attempt to read at the End-of-File fail, and thus both
the eofbit and the failbit end up set. This function can be used to check whether the failure is
due to reaching the End-of-File or to some other reason.
Output:
The internal error state flags are automatically set by calls to input/output functions on the stream
to signal certain errors