开发者

Why doesn't closing a file automatically clear error state?

开发者 https://www.devze.com 2023-03-02 16:16 出处:网络
When I use ifstream to read file, I loop over all lines in the file and close it. Then I try opening a different file with the same ifstream object, it still says the End-Of-File error. I\'m wondering

When I use ifstream to read file, I loop over all lines in the file and close it. Then I try opening a different file with the same ifstream object, it still says the End-Of-File error. I'm wondering why closing the file won't automatically clearing the state for me. I have to call clear() explictly after close() then.

Is there any reason why they design it like this? To me, that's really painful if you wanna reuse the fstream object for different files.

#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开发者_Go百科 I still get EOF error
    cout<<input.rdstate()<<endl;

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


Personally, I think close() should reset the flags, as I've been bitten by this in the past. Still, to mount my hobby-horse once more, your read code is wrong:

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

should be:

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

To see why, consider what happens if you try to read a completely empty file. The eof() call will return false (because although the file is empty, you have not yet read anything, and only reads set the eof bit) and you will output a line which does not exist.


The call to close may fail. When it does fail, it sets the failbit. If it reset the state of the stream, you wouldn't be able to check whether or not the call to close succeeded.


Because the flags are associated with the stream, not the file.


This has been changed in C++11 (C++0x), not so that close() discards any errors detected but the next open() will call clear() for you.

0

精彩评论

暂无评论...
验证码 换一张
取 消