当我ifstream用来读取文件时,我遍历文件中的所有行并关闭它.然后我尝试用同一个ifstream对象打开一个不同的文件,它仍然显示End-Of-File错误.我想知道为什么关闭文件不会自动为我清除状态.那之后我必须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;
}
}
Run Code Online (Sandbox Code Playgroud)
小智 5
就个人而言,我认为close()应该重置标志,因为我过去曾被这种情况所困扰.不过,为了再次登上我的爱好马,你的阅读代码是错误的:
while (!input.eof())
{
getline(input, line);
cout<<line<<endl;
}
Run Code Online (Sandbox Code Playgroud)
应该:
while (getline(input, line))
{
cout<<line<<endl;
}
Run Code Online (Sandbox Code Playgroud)
要了解原因,请考虑如果您尝试读取完全空的文件会发生什么.eof()调用将返回false(因为虽然文件为空,但您还没有读取任何内容,只有读取设置了eof位),您将输出一条不存在的行.