Mic*_*ann 2 c++ error-handling fstream
调用ifstream::close重置流failbit和/或badbit类似于调用clear吗?这不是这个问题的重复- 我需要知道标志是否被重置,而不仅仅是在它们被设置时.
例如,我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;
}
Run Code Online (Sandbox Code Playgroud)
在每个分支机构打电话myInputStream.close后,我是否必须接听电话myInputStream.fail才能获得准确的支票?或者这会工作:
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;
}
Run Code Online (Sandbox Code Playgroud)
我知道ifstream::close可以自己设置 failbit或者badbit如果关闭失败,这是我想在检查失败之前调用它的一个原因 - 无论是什么导致它我都需要返回false.如果关闭只进行一次,它看起来也不那么杂乱.
是否复位或如果别的东西已经设置它,使我的第二个代码示例返回真的吗?ifstream::close failbitbadbit
close()不应该清除任何状态标志,尽管它可能会failbit根据底层缓冲区的返回值进行设置.
[fstream.members](也是[ifstream.members]和[ofstream.members])
void close();效果:调用
rdbuf()->close(),如果该函数返回返回空指针,则调用setstate(failbit)(27.5.5.4)(可能抛出ios_base::failure).
但是,假设filebuf正确打开,则清除标志open()
void open(const char* s, ios_base::openmode mode = ios_base::in|ios_base::out);效果:通话
rdbuf()->open(s,mode).如果该函数没有返回空指针调用clear(),否则调用setstate(failbit)(可能抛出ios_base::failure)(27.5.5.4).