ifstream::close重置failbit和/或badbit

Does ifstream::close reset failbit and/or badbit?

本文关键字:badbit failbit close 重置 ifstream      更新时间:2023-10-16

调用ifstream::close是否复位流的failbit和/或badbit,类似于调用clear ?这不是这个问题的重复-我需要知道标志是否reset,而不仅仅是当它们set时。

例如,我在当前项目中使用if-else:

ifstream myInputStream("foo.txt");
//Let's pretend this compiles all the time, even though it
//might not because the operator is ambiguous.
myInputStream << "Outputting to an input stream causes problems."
if (myInputStream.fail())
{
   cout << "Aw, nuts. It failed." << endl;
   myInputStream.close();
   return false;
}
else
{
   cout << "No nuts here. Only chocolate chips." << endl;
   myInputStream.close();
   return true;
}

我是否必须在每个分支中调用myInputStream.fail之后调用myInputStream.close以获得准确的检查?或者这将工作:

ifstream myInputStream("foo.txt");
myInputStream << "Outputting to an input stream causes problems.";    
myInputStream.close();
if (myInputStream.fail())
{
   cout << "Aw, nuts. It failed." << endl;
   return false;
}
else
{
   cout << "No nuts here. Only chocolate chips." << endl;
   return true;
}

我知道ifstream::close可以自己设置 failbitbadbit,如果关闭失败,这是我想在检查失败之前调用它的一个原因-我需要返回false,不管什么原因导致它。如果闭包只执行一次,它看起来也不那么混乱。

tl;博士;

是否ifstream::close 重置 failbitbadbit,如果其他东西已经设置了它,使我的第二个代码示例返回真?

close()不应该清除任何状态标志,尽管它可能会根据底层缓冲区的返回值设置failbit

[fstream。[成员][ifstream.][ofstream.members])

void close();

Effects:调用rdbuf()->close(),如果该函数返回空指针,则调用setstate(failbit)(27.5.5.4)(可能抛出ios_base::failure)。

标志open()清除,但是,假设filebuf正确打开

void open(const char* s, ios_base::openmode mode = ios_base::in|ios_base::out);

Effects:调用rdbuf()->open(s,mode)。如果该函数没有返回空指针,则调用clear(),否则调用setstate(failbit),(可能抛出ios_base::failure)(27.5.5.4)。

使用问题中的示例代码(修改以使用g++编译),看起来ifstream::close 重置failbit。我不知道badbit,然而(ios::fail返回true如果设置)。

#include <fstream>
#include <iostream>
using namespace std;
int main()
{
   ofstream writer("foo.txt");
   writer << "These are not integers.";
   writer.close();
   ifstream myInputStream("foo.txt");
   int i;
   myInputStream >> i;//This should set the failbit.
   myInputStream.close();//Will this reset it?
   if (myInputStream.fail())
   {
      cout << "Aw, nuts. It failed." << endl;
      return false;
   }
   else
   {
      cout << "No nuts here. Only chocolate chips." << endl;
      return true;
   }
}

输出:哎呀!它失败了。

myInputStream.fail()返回false