[英]Check istreambuf_iterator fail
我们可以将整个文件读入一个字符串:
std::ifstream ifs(path);
assert(ifs.good());
std::string text(std::istreambuf_iterator<char>(ifs), std::istreambuf_iterator<char>())
一旦此代码返回一个空字符串。 如何检查读取过程中没有错误?
更新:
我了解到,如果一个文件正在被写入(或刚刚被覆盖),那么当我读取该文件时,std::filesystem::file_size 可能返回 0,并且 ifstream 从 operator bool 返回 true(在 Windows 上)。 所以该文件在一段时间内不可用,但我没有收到任何错误,我无法将这种情况与真正的空文件的情况区分开来。 所以我必须在循环中读取一个文件,而它的大小为 0 一段时间。
检查流是否有错误的最简单方法是在对流进行每次操作后使用operator bool 。
#include <iostream>
#include <fstream>
#include <string>
int main()
{
std::string file_name{"data.txt"};
std::ifstream ifs(file_name);
if ( !ifs) // <---
std::cout << "Error: unable to open " << file_name << ".\n";
std::string text{ std::istreambuf_iterator<char>(ifs),
std::istreambuf_iterator<char>() };
// ^ ^
if ( ifs ) // <--
std::cout << text << '\n';
else
std::cout << "An error occured while reading the file.\n";
}
请注意,OP 的代码段受到Most Vexing Parse 的影响,可以使用字符串的 列表初始化来修复。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.