[英]How to check for I/O errors when using “ifstream”, “stringstream” and “rdbuf()” to read the content of a file to string?
我正在使用以下方法将文件的内容读入字符串:
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
的插入失败,将在buffer
上设置failbit
。
你可以使用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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.