【问题标题】:Check istreambuf_iterator fail检查 istreambuf_iterator 失败
【发布时间】:2019-12-11 21:51:56
【问题描述】:

我们可以将整个文件读入一个字符串:

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 从 operator bool 返回 true(在 Windows )。所以文件在一段时间内不可用,但我没有收到任何错误,我无法将这种情况与真正的空文件情况区分开来。所以我必须在一个循环中读取一个文件,而它的大小是 0 一段时间。

【问题讨论】:

    标签: c++


    【解决方案1】:

    检查流是否有错误的最简单方法是在对流进行每次操作后使用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 的 sn-p 受到 Most Vexing Parse 的影响,可以使用字符串的 list-initialization 修复。

    【讨论】:

    • 我了解到,如果正在写入(或刚刚写入)文件,那么当我读取文件时,std::filesystem::file_size 可能会返回 0,而 ifstream 从运算符布尔。所以文件在一段时间内不可用,但我没有收到任何错误,我无法将这种情况与真正的空文件情况区分开来。所以我必须循环读取一个文件,而它的大小是 0 一段时间。
    • @EmilKabirov 我不知道,但这听起来像是操作系统/实现问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-25
    • 2016-05-31
    • 2017-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多