使用"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?
我使用以下方法将文件的内容读入字符串:
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
相关文章:
- valgrind-hellgrind与泄漏检查的结果不同
- C++模板来检查友元函数的存在
- 检查输入是否不是整数或数字
- 试图让变量检查数组中的某些内容
- 检查值是否在集合p1和p2中,但不在p3中
- C++概念:如何使用'concept'检查模板化结构的属性?
- 概念TS检查忽略私有访问修饰符
- 检查 std::shared_ptr<> 的当前底层类型是否为 T
- 在c++中检查长方体是否尽可能快地重叠(无迭代)
- 如何在C++中检查2D数组中负值的输入验证
- C++:正在检查LinkedList中的回文-递归方法-错误
- 使用for循环检查数组中的重复项
- 如何检查一个c++字符串中有多少相同的字符/数字
- 检查不带转换的扫描格式
- 如何检查线程是否锁定
- 清除前检查矢量
- 如何处理来自核心指南检查器的关于gsl::at的静态分析警告
- C++LDAP检查用户是否是特定组的成员
- 我如何循环循环switch语句检查重新检查char?(C )
- Visual Studio - 如何从 C++ 核心指南检查器检查路径中排除文件夹