c++ - VS8 无法处理 file.close(); file.open();,为什么?

标签 c++

我有一个可能微不足道的问题,但我无法理解。 我写了简单的代码:

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/

相关文章:

c++ - Google 测试中的 "Assert and return"宏?

c++ - 维护堆属性

c++ - remove_if : Predicate error when passing a function returning bool

Android:如何正确链接我自己的静态库?

c++ - 如何让 Valgrind 记录所有分配?

c++ - 如何在 QPlainTextEdit 中捕获链接点击事件

c++ - 类型嵌套在模板类中的部分特化

c++ - 为什么 CAF system.registry() 应该在 put(atom_value) 之后自动调用 erase(atom_value)

c++ - 在后端运行成员函数而不减慢主应用程序的技巧是什么?

c++ - C++中的指针初始化