Sometimes during file operations, errors may Occur.
Let us take ann 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.
To find the solution 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. The current state of the I/O system is held in an integer, in which the following flags are encoded :
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 |
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 bad() | Returns a non-zero value if an invalid operation is attempted or any unrecoverable error has occurred. However, if it is zero (false value), it may be possible to recover from any other error reported and continue operations. |
int eof() | Returns non-zero (true value) if end-of-file is encountered while reading; otherwise returns zero (false value). |
int fail() | Returns non-zero (true) when an input or output operation has failed. |
int good() | 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 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. |
Comments