C++ error handling In file
So far we have been opening and using the files for reading and writing on the assumption that everything is sine with the files. This may not be true always.for instance any one of the following things may happen when dealing with the files .
1. A file that which we are attempting to open for reading does not exist.
2. The file name used to new file may already exist.
3. we may attempt an valid operation such as reading past the end of file.
4. There may not be minimum space in the disk for storing more data.
5. We may use any invalid file name.
6. we may attempt to perform an operation when the file is not opened for that specific purpose
C++ language file stream inherits a stream state member from the class ios. This member records all information on the status of the file that is being currently used. The stream state member uses bit fields to store
The status of the error conditions stated above.
The class ios(input output stream) supports several member functions that can be used to read the status recorded in a file stream.
These functions along with their meanings are in the below table
ERROR Handling Functions
FUNCTION |
Return value and meaning |
eof() |
Returns true (non zero value) if end of file is encountered while reading
|
fails() |
Returns true when an input or output operation has failed |
bad() |
Returns true of an invalid operation is attempted or any unrecoverable error has occurred. however if it is false it may be possible to recover from any other error report, and continue operation
|
good() |
Returns true of 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(I/O) operations. when it returns false no further operations can be carried out. |
These functions may be used in the appropriate places in a program to locate the status of a file stream and thereby to take the necessary corrective measures
………..
……….
ifstream infile;
infile.open(“ABC”);
(!infile.fail())
{
………..
……….
}
(infile.eof())
{
…….
…… (terminate program normally )
}
(infile.bad()))
{
……..
report error
}
{
infile.clear();
…..
}
|
The function clear() which we used in the previous section as well resets the error state so that further operations can be attempted
Remember That we have already used statement such as
(infile)
{
…..
…..
}
and
{
……….
}
|
Here infile becomes false (zero) when end of the file is reached (and eof() becomes true)