You can not. The standard says getline :
If the function does not extract any characters, it calls is.setstate(ios_base::failbit) , which can throw ios_base::failure (27.5.5.4).
If your file ends with an empty line, i.e. the last character is "\ n", then the last getline call does not read the characters and is not executed. Indeed, how do you want the loop to end if it did not set failbit? The while condition will always be true, and it will work forever.
I think you misunderstand what failbit means. This does not mean that the file cannot be read. Rather, it is used as the flag that completed the last operation. Bitbud is used to indicate a low-level error, but it is little used for standard file streams. failbit and eofbit should not usually be interpreted as exceptional situations. badbit, on the other hand, and I would say that fstream :: open should have set badbit instead of failbit.
In any case, the above code should be written as:
try { ifstream inf(argv[1]); if(!inf) throw SomeError("Cannot open file", argv[1]); string line; while(getline(inf,line)) cout << line << endl; inf.close(); } catch(const std::exception& e) { cout << e.what() << endl; }
source share