ifstream::close 会重置 failbit and/or badbit 吗?

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

是否调用 ifstream::close reset the stream's failbit and/or badbit, similar to calling clear? This is not a duplicate of this question- 我需要知道标志是否 重置 ,而不仅仅是当它们 设置 .

例如,我在我当前的项目中使用类似下面的东西 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 如果关闭失败,这是我想调用它的原因之一在检查失败之前 - 我需要 return false 不管是什么原因造成的。如果关闭只完成一次,它看起来也不那么混乱。

tl;dr;

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

使用问题中的示例代码(修改后使用 g++ 编译),看起来 ifstream::close does not reset failbit. I don't know about badbit, however (ios::fail returns 如果设置了其中一个则为真。

#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。

close() 不应清除任何状态标志,尽管它可能会根据基础缓冲区的 return 值设置 failbit

[fstream.members](还有 [ifstream.members] 和 [ofstream.members])

void close();

Effects: Calls rdbuf()->close() and, if that function returns returns a null pointer, calls setstate(failbit) (27.5.5.4) (which may throw ios_base::failure).

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

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

Effects: Calls rdbuf()->open(s,mode). If that function does not return a null pointer calls clear(), otherwise calls setstate(failbit), (which may throw ios_base::failure) (27.5.5.4).