【发布时间】: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”中读取,但这确实看起来很奇怪,不是吗?