3

I would like to know in what case we can have :

bool(std::ifstream) != std::ifstream::good()

The difference is that bool(std::ifstream) does not test the eof bit whereas std::ifstream::good() tests it. But practically, the eof bit is raised if one try to read something after the end of the file. But as soon as you try to do this I think that either fail or bad bit is also set.

Consequently in what case you can only raise the eof bit ?

Vincent
  • 57,703
  • 61
  • 205
  • 388
  • You can manually set the eof bit independently of the other error flags, but I'm not sure under what circumstances you would do so. `std::ifstream::setstate(std::ios::eofbit)`. – nebain May 15 '13 at 02:08

1 Answers1

0

Simply put, whenever you encounter the end of a file without attempting to read behind it. Consider a file "one.txt" which contains exactly one single '1' character.

Example for unformatted input:

#include <iostream>
#include <fstream>

int main()
{
    using namespace std;
    char chars[255] = {0};
    ifstream f("one.txt");
    f.getline(chars, 250, 'x');
    cout << f.good() << " != " << bool(f) << endl;
    return 0;
}

0 != 1
Press any key to continue . . .

Example for formatted input:

#include <iostream>
#include <fstream>

int main()
{
    using namespace std;
    ifstream f("one.txt");
    int i; f >> i;
    cout << f.good() << " != " << bool(f) << endl;
    return 0;
}

0 != 1
Press any key to continue . . .

danielschemmel
  • 10,885
  • 1
  • 36
  • 58