C++ ifstream failbit and badbit
Solution 1:
According to cplusplus.com:
failbit is generally set by an input operation when the error was related to the internal logic of the operation itself, so other operations on the stream may be possible. While badbit is generally set when the error involves the loss of integrity of the stream, which is likely to persist even if a different operation is performed on the stream. badbit can be checked independently by calling member function bad.
In simple words, if you get a number when expect to retrieve a letter, it's failbit
. If a serious error happens, which disrupts the ability to read from the stream at all - it's a badbit
.
Except mentioned flags there is a third quite similar — eofbit
. You can check the state using several functions: ios::fail
, ios::good
and ios::bad
And you can get familiar with iostream library at MSDN resource too.
Finally, if you search for the correct solution of how to handling all error bits and exceptions while reading from the file (or accessing some file or directory), I highly recommend you read a very comprehensive and well-written article "Reading files in C++ using ifstream: dealing correctly with badbit, failbit, eofbit, and perror()", at the end of which you will find a few Ideal solutions. The article is worth to read indeed.