How to check I / O errors when using "ifstream", "stringstream" and "rdbuf ()" to read the contents of a file into a string?

I use the following method to read the contents of a file into a string:

std::ifstream t("file.txt"); std::stringstream buffer; buffer << t.rdbuf(); std::string data(buffer.str()); 

But how can I check for I / O errors and make sure that all the content has actually been read?

+6
source share
3 answers

You can do this the same way as with any other insert operation:

 if (buffer << t.rdbuf()) { // succeeded } 

If fetching from t.rdbuf() or inserting into buffer fails, failbit will be set to buffer .

+5
source

You can use t.good ().
You can see the description at http://www.cplusplus.com/reference/iostream/ios/good/

+1
source

t.good() was mentioned by bashor

Note that t.good() != t.bad() ; You can use !t.bad() (or !t.fail() !t.eof() for certain conditions)

I usually use

 if (!t.bad()) { // go ahead if no _unpexpected errors } if (!t.fail()) t.clear(); // clear any _expected_ errors 
0
source

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


All Articles