C++ ifstream failbit and badbit

C++File IoIfstream

C++ Problem Overview


In case of ifstream in C++, under what conditions are failbit and badbit flags set ?

C++ Solutions


Solution 1 - C++

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJakeView Question on Stackoverflow
Solution 1 - C++Sergei DanielianView Answer on Stackoverflow