简体   繁体   English

使用“ifstream”,“stringstream”和“rdbuf()”将文件内容读入字符串时如何检查I / O错误?

[英]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? 但是,如何检查I / O错误并确保实际读取了所有内容?

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 . 如果从t.rdbuf()的提取或buffer的插入失败,将在buffer上设置failbit

You can use t.good(). 你可以使用t.good()。
You can look description on http://www.cplusplus.com/reference/iostream/ios/good/ 您可以在http://www.cplusplus.com/reference/iostream/ios/good/上查看说明

t.good() was mentioned by bashor t.good()被bashor提到

Note though, that t.good() != t.bad() ; 但请注意, t.good() != t.bad() ; You may want to use !t.bad() (or !t.fail() , !t.eof() for specific conditions) 您可能想要使用!t.bad() (或!t.fail() !t.eof()用于特定条件)

I usually use 我经常使用

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

} 

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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