ifstream::close重置failbit和/或badbit
Does ifstream::close reset failbit and/or badbit?
调用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
可以自己设置 failbit
或badbit
,如果关闭失败,这是我想在检查失败之前调用它的一个原因-我需要返回false,不管什么原因导致它。如果闭包只执行一次,它看起来也不那么混乱。
tl;博士;
是否ifstream::close
重置 failbit
或badbit
,如果其他东西已经设置了它,使我的第二个代码示例返回真?
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
- cin.clear(ios_base::failbit) vs cin.setstate(ios_base::failb
- C++ Inheriting from iostream failbit set
- 为什么即使输入有效,也总是设置 cin.failbit
- C 从二进制文件和failbit中读取布尔值
- 管道到 /dev/null 时出现未指定的iostream_category错误(iOS::badbit 问题?
- 为什么是下面的's.clear(ios::badbit);?为什么不是's.clear(ios::failbit);'
- 为什么要iStream ::获得sets failbit和eofbit在一起
- 文件读取失败,出现ios_base::failbit
- C++ ifstream failbit and badbit
- C++三维模型io、二进制文件读取(badbit)和#DEN问题
- ifstream::close重置failbit和/或badbit
- 使用getline()而不设置failbit
- istream提取没有明显原因地设置failbit
- Ifstream在读取文本文件时设置failbit
- 在c++中执行getline函数调用时,何时设置failbit ?
- 为什么设置了failbit()