为什么不自动关闭文件清除错误状态?

时间:2011-05-01 16:15:01

标签: c++ fstream

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

为什么他们这样设计呢?对我来说,如果你想将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;
    }
}

4 个答案:

答案 0 :(得分:5)

就我个人而言,我认为close()应该重置标志,因为我过去曾被这种情况所困扰。不过,为了再次登上我的爱好马,您的阅读代码是错误的:

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

应该是:

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

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

答案 1 :(得分:3)

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

答案 2 :(得分:1)

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

答案 3 :(得分:0)

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