简体   繁体   English

检查 istreambuf_iterator 失败

[英]Check istreambuf_iterator fail

We can read a whole file into a string:我们可以将整个文件读入一个字符串:

std::ifstream ifs(path);
assert(ifs.good());
std::string text(std::istreambuf_iterator<char>(ifs), std::istreambuf_iterator<char>())

Once this code returned an empty string.一旦此代码返回一个空字符串。 How can I check that there were no errors during the reading?如何检查读取过程中没有错误?

UPD:更新:

I've learned that if a file is being written (or just have been overwritten), then when I read the file, std::filesystem::file_size may return 0, and ifstream returns true from operator bool (on Windows).我了解到,如果一个文件正在被写入(或刚刚被覆盖),那么当我读取该文件时,std::filesystem::file_size 可能返回 0,并且 ifstream 从 operator bool 返回 true(在 Windows 上)。 So the file is not available for some time, but I get no errors and I can't distinguish this case from a case of real empty file.所以该文件在一段时间内不可用,但我没有收到任何错误,我无法将这种情况与真正的空文件的情况区分开来。 So I have to read a file in a loop while its size is 0 for some time.所以我必须在循环中读取一个文件,而它的大小为 0 一段时间。

The easiest way to check whether the stream has errors is to use operator bool after every operation on streams.检查流是否有错误的最简单方法是在对流进行每次操作后使用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";
}

Note that OP's snippet suffers from the Most Vexing Parse , which can be fixed using the list-initialization of the string.请注意,OP 的代码段受到Most Vexing Parse 的影响,可以使用字符串的 列表初始化来修复。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM