使用"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?

本文关键字:检查 何检查 错误 字符串 stringstream ifstream rdbuf 读取 使用 文件      更新时间:2023-10-16

我使用以下方法将文件的内容读入字符串:

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

但是我如何检查I/O错误并确保所有的内容实际上已经被读取?

您可以按照与其他插入操作相同的方式执行:

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

如果从t.rdbuf()提取或插入buffer失败,则failbit将设置在buffer上。

你可以使用t.good()。
您可以查看http://www.cplusplus.com/reference/iostream/ios/good/

上的描述。

t.good()被bashor提到

请注意,t.good() != t.bad();您可能希望使用!t.bad()(或!t.fail(), !t.eof()用于特定的条件)

我通常用

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