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(...)