David Sykes
David Sykes

Reputation: 49872

ifstream.read fails on an existing file if a previous open fails

In my code an ifstream object tries to open a non existing file, which fails, then opens an existing file which succeeds. However the subsequent read fails.

If the existing file is opened without a previous fail then the read succeeds.

What clean up am I missing after the open fails?

The following code

#include <iostream>
#include <fstream>

int main(int argc, char* argv[])
{
    char *buf = new char[10];

    std::ifstream ifstr;

    ifstr.open("ExistingFile.txt", std::ios_base::in | std::ios_base::binary);
    std::cout << ifstr.is_open() << std::endl;
    ifstr.read(buf, 4);
    std::cout << ifstr.fail() << std::endl;
    ifstr.close();

    ifstr.open("NonExistingFile.txt", std::ios_base::in | std::ios_base::binary);
    std::cout << ifstr.is_open() << std::endl;
    ifstr.read(buf, 4);
    std::cout << ifstr.fail() << std::endl;
    ifstr.close();

    ifstr.open("ExistingFile.txt", std::ios_base::in | std::ios_base::binary);
    std::cout << ifstr.is_open() << std::endl;
    ifstr.read(buf, 4);
    std::cout << ifstr.fail() << std::endl;
    ifstr.close();

    return 0;
}

produces

1
0
0
1
1
1

Upvotes: 1

Views: 1470

Answers (2)

Raul Andres
Raul Andres

Reputation: 3806

You should clear ( ifstr.clear() ) previous errors

If you clear the stream before closing if, ifstr.close() will likely set the ifstr fail flag. Don't close the stream if is_open() fails

Upvotes: 3

Jay
Jay

Reputation: 607

You may need to add ifstr.clear(); after ifstr.close(); to clear the fail bits.

Upvotes: 3

Related Questions