Reputation: 569
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.
Upvotes: 0
Views: 373
Reputation: 12779
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.
Upvotes: 1