当我使用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;
}
}
你为什么要阅读输出^ _ ^? – alternative 2011-05-01 16:17:09
@mathepic,您可以随时阅读输出文件,但不能写入输入文件。无论如何,这个名字应该不重要:) – 2011-05-01 16:20:23
我当然可以写入一个“input.txt”,并从“output.txt”中读取,但这看起来确实很奇怪,不是吗? – alternative 2011-05-01 16:53:34