Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm using the following method to read the content of a file into a string:

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

But how do I check for I/O errors and ensure that all the content has actually been read?

like image 214
gablin Avatar asked Oct 30 '11 16:10

gablin


2 Answers

You can do it the same way you would do it with any other insertion operation:

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

If either the extraction from t.rdbuf() or the insertion to buffer fails, failbit will be set on buffer.

like image 130
avakar Avatar answered Oct 06 '22 00:10

avakar


You can use t.good().
You can look description on http://www.cplusplus.com/reference/iostream/ios/good/

like image 21
bashor Avatar answered Oct 05 '22 23:10

bashor