【问题标题】:Why doesn't closing a file automatically clear error state?为什么关闭文件不会自动清除错误状态?
【发布时间】:2011-05-01 16:15:01
【问题描述】:

当我使用ifstream 读取文件时,我会遍历文件中的所有行并关闭它。然后我尝试使用相同的 ifstream 对象打开另一个文件,它仍然显示 End-Of-File 错误。我想知道为什么关闭文件不会自动为我清除状态。我必须在close() 之后明确地打电话给clear()

他们有什么理由这样设计它?对我来说,如果你想为不同的文件重用 fstream 对象,那真的很痛苦。

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

void main()
{
    ifstream input;
    input.open("c:\\input.txt");

    string line;
    while (!input.eof())
    {
        getline(input, line);
        cout<<line<<endl;
    }

    // OK, 1 is return here which means End-Of-File
    cout<<input.rdstate()<<endl;

    // Why this doesn't clear any error/state of the current file, i.e., EOF here?
    input.close();

    // Now I want to open a new file
    input.open("c:\\output.txt");

    // But I still get EOF error
    cout<<input.rdstate()<<endl;

    while (!input.eof())
    {
        getline(input, line);
        cout<<line<<endl;
    }
}

【问题讨论】:

  • 为什么要读取输出^_^?
  • @mathepic,您始终可以读取输出文件,但不能写入输入文件。无论如何,这个名字应该不重要:)
  • 我当然可以写入“input.txt”,并从“output.txt”中读取,但这确实看起来很奇怪,不是吗?

标签: c++ fstream


【解决方案1】:

就我个人而言,我认为 close() 应该重置标志,因为我过去一直被这个问题所困扰。不过,要再次安装我的爱好马,您读取的代码是错误的:

while (!input.eof())
 {
    getline(input, line);
    cout<<line<<endl;
 }

应该是:

while (getline(input, line))
 {
     cout<<line<<endl;
 }

要了解原因,请考虑如果您尝试读取一个完全空的文件会发生什么。 eof() 调用会返回 false(因为虽然文件是空的,但你还没有读取任何内容,只读取设置了 eof 位)并且你会输出一个不存在的行。

【讨论】:

    【解决方案2】:

    close 的调用可能会失败。当它确实失败时,它会设置failbit。如果它重置流的状态,您将无法检查对close 的调用是否成功。

    【讨论】:

    • OK.. 但是只有在关闭失败时他们才能设置状态。
    • 然后他们必须测试所有的失败条件,而在当前的实现中,只有一个测试成功。
    • 但是有没有人测试过关闭失败?我知道我从不这样做。如果它确实失败了你会怎么做?
    【解决方案3】:

    因为标志与流相关联,而不是文件。

    【讨论】:

      【解决方案4】:

      这已在 C++11 (C++0x) 中进行了更改,因此 close() 不会丢弃检测到的任何错误,但下一个 open() 为您调用 clear()。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-05-31
        • 1970-01-01
        • 1970-01-01
        • 2021-10-12
        • 2014-10-01
        相关资源
        最近更新 更多