Use getline () without installing failbit

Is it possible to use getline() to read a valid file without installing failbit ? I would like to use failbit so that an exception is thrown if the input file is not readable.

The following code always displays basic_ios::clear as the last line - even if a valid input is specified.

test.cc:

 #include <iostream> #include <string> #include <fstream> using namespace std; int main(int argc, char* argv[]) { ifstream inf; string line; inf.exceptions(ifstream::failbit); try { inf.open(argv[1]); while(getline(inf,line)) cout << line << endl; inf.close(); } catch(ifstream::failure e) { cout << e.what() << endl; } } 

input.txt:

 the first line the second line the last line 

results:

 $ ./a.out input.txt the first line the second line the last line basic_ios::clear 
+6
source share
1 answer

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; } 
+6
source

Source: https://habr.com/ru/post/899830/


All Articles