0

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.

Emil Kabirov
  • 559
  • 4
  • 14

1 Answers1

1

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.

Bob__
  • 12,361
  • 3
  • 28
  • 42
  • I've learned that if a file is being written (or just have been written), then when I read the file, std::filesystem::file_size may return 0, and ifstream returns true from operator bool. 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. – Emil Kabirov Dec 15 '19 at 21:17
  • @EmilKabirov I was unaware of that, but it sounds like an OS/implementation problem. – Bob__ Dec 16 '19 at 09:38