简体   繁体   中英

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). 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.

The easiest way to check whether the stream has errors is to use operator bool after every operation on streams.

#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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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