0

When executing the following code, I get the following output: EOF FAIL. So reading a line from an empty file sets eofbit and failbit, but not badbit.

If I enable exceptions by uncommenting line 11 the output changes: EOF BAD FAIL. Now reading a line from an empty file sets eofbit, badbit, but not failbit (otherwise an exception had occured).

Can someone explain why enabling exceptions changes the way, failbit and badbit are set. Is this documented somewhere?

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main(int argc, char const *argv[]) {
    ifstream f("some_empty_file");
    string line;

    // f.exceptions(std::ifstream::failbit); // (line 11)

    getline(f, line);
    if(f.eof()) cout << "EOF ";
    if(f.bad()) cout << "BAD ";
    if(f.fail()) cout << "FAIL ";

    cout << endl;
    f.close();

    return 0;
}

Edit: I read the answer on https://stackoverflow.com/a/11085193/3821618 on the difference of badbit and failbit. But that does not answer the question, why with exceptions enabled, reading from an empty file becomes a "serious error", while it is not, if I do not call f.exceptions(...)

JAyP
  • 75
  • 5

1 Answers1

0

There are 4 distinct stream states (taken from std::ios_base::iostate):

 typedef /*implementation defined*/ iostate;
 static constexpr iostate goodbit = 0;
 static constexpr iostate badbit = /*implementation defined*/
 static constexpr iostate failbit = /*implementation defined*/
 static constexpr iostate eofbit = /*implementation defined*/

So setting of the eofbit doesn't necessarily trigger your exception mask.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
  • Neither with nor without the call to `f.exception(..)` an exception is triggered. It it only the result of `f.bad()` that changes. Why so? – JAyP Jun 04 '17 at 14:28
  • @JAyP [I can't really see any behavior changing](http://coliru.stacked-crooked.com/a/bd1d35f7aa25fcb3)? – πάντα ῥεῖ Jun 04 '17 at 14:35
  • Interesting: no changing behavior with gcc5.4 on gnu/linux, but **it does change** with clang-800.0.42.1 on macos. I did not thought of this to be platform depended. Thanks for your answer. – JAyP Jun 04 '17 at 14:56
  • @JAyP There are the `/*implementation defined*/` comments. – πάντα ῥεῖ Jun 04 '17 at 14:58