C++ 检查istreambuf_迭代器失败
我们可以将整个文件读入字符串:C++ 检查istreambuf_迭代器失败,c++,C++,我们可以将整个文件读入字符串: std::ifstream ifs(path); assert(ifs.good()); std::string text(std::istreambuf_iterator<char>(ifs), std::istreambuf_iterator<char>()) 一旦此代码返回一个空字符串。如何检查阅读过程中是否没有错误 UPD: 我了解到,如果一个文件正在写入或刚刚被覆盖,那么当我读取该文件时,std::filesystem::fil
std::ifstream ifs(path);
assert(ifs.good());
std::string text(std::istreambuf_iterator<char>(ifs), std::istreambuf_iterator<char>())
一旦此代码返回一个空字符串。如何检查阅读过程中是否没有错误
UPD:
我了解到,如果一个文件正在写入或刚刚被覆盖,那么当我读取该文件时,std::filesystem::file_size可能返回0,而ifstream从Windows上的操作符bool返回true。因此,该文件在一段时间内不可用,但我没有收到任何错误,并且我无法将此情况与实际的空文件情况区分开来。所以我必须在一段时间内读取一个循环中的文件,而它的大小为0 检查流是否有错误的最简单方法是在每次对流执行操作后使用
#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的代码段存在错误,可以使用字符串的名称修复错误。我了解到,如果文件正在写入或刚刚写入,那么当我读取文件时,std::filesystem::file_size可能会返回0,而ifstream从操作符bool返回true。因此,该文件在一段时间内不可用,但我没有收到任何错误,并且我无法将此情况与实际的空文件情况区分开来。所以我必须在循环中读取一个文件,而它的大小为0有一段时间。@EmilKabirov我没有意识到这一点,但这听起来像是OS/实现问题。