Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ ifstream failbit and badbit

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

like image 954
Jake Avatar asked Jun 18 '12 14:06

Jake


1 Answers

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.

like image 130
Sergei Danielian Avatar answered Sep 23 '22 11:09

Sergei Danielian