C++ ifstream failbit 和 badbit

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11085151/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 14:50:12  来源:igfitidea点击:

C++ ifstream failbit and badbit

c++file-ioifstream

提问by Jake

In case of ifstreamin C++, under what conditions are failbitand badbitflags set ?

在的情况下,ifstream在C ++中,根据条件是什么failbitbadbit标志设置?

回答by gahcep

According to cplusplus.com:

根据cplusplus.com

failbitis 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 badbitis 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.

当错误与操作本身的内部逻辑相关时,failbit通常由输入操作设置,因此流上的其他操作可能是可能的。虽然当错误涉及流的完整性丢失时,通常会设置badbit,即使对流执行不同的操作,它也可能持续存在。badbit 可以通过调用成员函数 bad 来独立检查。

In simple words, if you get a numberwhen expect to retrieve a letter, it's failbit. If a seriouserror happens, which disrupts the ability to read from the stream at all - it's a badbit.

简单的话,如果你得到一个号码时,希望取回信件,它的failbit。如果发生严重错误,这会完全破坏从流中读取的能力 - 它是一个badbit.

Except mentioned flags there is a third quite similar — eofbit. You can check the state using several functions: ios::fail, ios::goodand ios::bad

除了提到的标志外,还有第三个非常相似 - eofbit. 您可以使用以下几个函数检查状态:ios::fail,ios::goodios::bad

And you can get familiar with iostream libraryat MSDN resource too.

您也可以在 MSDN 资源中熟悉iostream 库

Finally, if you search for the correctsolution 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.

最后,如果您在从文件读取(或访问某些文件或目录)时寻找如何处理所有错误位和异常的正确解决方案,我强烈建议您阅读一篇非常全面且写得很好的文章“用 C++ 读取文件使用 ifstream:正确处理 badbit、failbit、eofbit 和 perror()”,最后你会找到一些理想的解决方案。这篇文章确实值得一读。