gpt4 book ai didi

c++ - ifstream::close 是否会重置 failbit 和/或 badbit?

转载 作者:搜寻专家 更新时间:2023-10-31 00:11:46 24 4
gpt4 key购买 nike

是否调用 ifstream::close重置流的 failbit 和/或 badbit,类似于调用 clear ?这不是 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,这是我想在检查失败之前调用它的原因之一——我需要返回 false不管是什么原因造成的。如果闭包只执行一次,它看起来也不那么困惑。

tl;dr;

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

最佳答案

close() 不应清除任何状态标志,尽管它可能会根据底层缓冲区的返回值设置 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).

关于c++ - ifstream::close 是否会重置 failbit 和/或 badbit?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32833632/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com