gablin
gablin

Reputation: 4798

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?

Upvotes: 7

Views: 1652

Answers (3)

sehe
sehe

Reputation: 393457

t.good() was mentioned by bashor

Note though, that t.good() != t.bad(); You may want to use !t.bad() (or !t.fail(), !t.eof() for specific conditions)

I usually use

if (!t.bad())
{
     // go ahead if no _unpexpected errors

} 

if (!t.fail())
   t.clear(); // clear any _expected_ errors

Upvotes: 1

bashor
bashor

Reputation: 8453

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

Upvotes: 2

avakar
avakar

Reputation: 32635

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.

Upvotes: 6

Related Questions