C++ ifstream failbit and badbit

微笑、不失礼 提交于 2019-12-17 08:55:25

问题


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


回答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.



来源:https://stackoverflow.com/questions/11085151/c-ifstream-failbit-and-badbit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!