2011-05-01 73 views
2

当我使用ifstream来读取文件时,我将遍历文件中的所有行并关闭它。然后我尝试用同一个ifstream对象打开一个不同的文件,但仍然说文件结尾错误。我想知道为什么关闭文件不会自动为我清除状态。那么我必须在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; 
    } 
} 
+0

你为什么要阅读输出^ _ ^? – alternative 2011-05-01 16:17:09

+0

@mathepic,您可以随时阅读输出文件,但不能写入输入文件。无论如何,这个名字应该不重要:) – 2011-05-01 16:20:23

+0

我当然可以写入一个“input.txt”,并从“output.txt”中读取,但这看起来确实很奇怪,不是吗? – alternative 2011-05-01 16:53:34

回答

3

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

+1

行..但是只有在关闭失败的情况下,他们才能设置状态。 – 2011-05-01 16:33:19

+0

然后,他们将不得不测试所有失败的条件,而在目前的实施中,只有一个成功的测试。 – Dikei 2011-05-01 17:08:24

+0

但有没有人测试过关闭失败?我知道我从来不会这样做。如果它失败了,你会怎么做? – 2011-05-01 17:45:18

1

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

5

就我个人而言,我认为close()应该重置标志,因为过去我一直被这个标志咬住。不过,一旦安装我的爱好马多,你读的代码是错误的:

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

应该是:

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

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

+0

这是一个很好的观点,谢谢。 – 2011-05-01 16:33:42

0

这已在C++ 11(C++ 0x)中进行了更改,并非如此,close()会丢弃检测到的任何错误,但下一次打开()将为您调用clear()。

相关问题