我有一个可能微不足道的问题,但我无法理解。 我写了简单的代码:
fstream file;
file.open("data", ios::in);
if(!file.good()){
file.close();
file.open("data", ios::out);
if(!file.good()) cout<<"not good"<<endl;
file<<"test"<<endl;
file.close();
}
在新的 VS8 C++ Express 项目中。当我运行它并且“数据”不存在时,它会创建文件,但也会返回“不好”(第二个),因此输出不会写入文件。现在有趣的事情来了。如果我在 VS10 C++ Express 和 Code::Blocks 12 中编译相同的代码,它工作正常。
为什么会这样?
@编辑 我的 friend 也在他的 PC 上用 VS8 C++ Expres 检查了它。对他也一样。
@edit2 与我对“解决方案”的评论相同:
Forcing to clear failbit with .clear(); method seems to work. It hurts when you learn in newer IDE and then has to switch to older one :/. Tho, it gives nice lesson. Thanks guys.
最佳答案
这是设计使然。在 C++98 中,关闭 fstream 不会清除错误状态,并且在 fstream 上调用 open()
不会重置错误状态。参见 LWG Defect #409讨论这个问题。
C++11 中的行为已更改,如果打开操作成功,错误状态将被清除(通过调用 clear()
)。
关于c++ - VS8 无法处理 file.close(); file.open();,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17052706/