简体   繁体   中英

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?

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 .

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM