C++ 为什么';关闭文件是否会自动清除错误状态?
当我使用C++ 为什么';关闭文件是否会自动清除错误状态?,c++,fstream,C++,Fstream,当我使用ifstream读取文件时,我循环文件中的所有行并关闭它。然后,我尝试使用相同的ifstream对象打开另一个文件,它仍然显示文件结束错误。我想知道为什么关闭文件不会自动为我清除状态。我必须在close()之后明确地调用clear() 他们这样设计有什么原因吗?对我来说,如果你想为不同的文件重用fstream对象,那真的很痛苦 #include <iostream> #include <fstream> #include <string> using
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;
}
}
#包括
#包括
#包括
使用名称空间std;
void main()
{
ifstream输入;
input.open(“c:\\input.txt”);
弦线;
而(!input.eof())
{
getline(输入,行);
cout因为标志与流关联,而不是与文件关联。对关闭的调用可能会失败。当它失败时,它会设置失败位。如果它重置流的状态,你将无法检查对关闭
的调用是否成功。我个人认为关闭()应该重新设置标志,因为我在过去被它咬过。但是,要再次骑上我的嗜好马,您的读取代码是错误的:
while (!input.eof())
{
getline(input, line);
cout<<line<<endl;
}
while(!input.eof())
{
getline(输入,行);
cout这在C++11(C++0x)中已被更改,不是因为close()会丢弃检测到的任何错误,而是下一个open()会为您调用clear()。为什么您要读取output^^?@mathepic,您总是可以读取输出文件,但无法写入输入文件。无论如何,这个名称不重要:)我当然可以写入“input.txt”,并从“output.txt”读取,但这显然是一件很奇怪的事情,不是吗?好吧。但他们只能在close失败时设置状态。然后他们必须测试所有失败条件,而在当前的实现中,只有一个测试成功。但是有人测试过close失败吗?我知道我从不这样做。如果失败了,你会怎么做?
while (getline(input, line))
{
cout<<line<<endl;
}