You can use the rdstate utilities to examine (and reset if needed) the state of the input file stream.
In your program this would for instance work as follows:
#include <iostream>
#include <fstream>
#include <string>
int main()
{
std::ifstream file("sample.txt");
std::string content = std::string((
std::istreambuf_iterator<char>(file)),
std::istreambuf_iterator<char>());
std::cout << "Reading status: " << file.rdstate() << std::endl;
if (file.rdstate())
std::cout << "Reading the file failed" << std::endl;
return 0;
}
The first output is for demonstration - file.rdstate
will be 0 if everything went well. If something went wrong it's value will be a system dependent sum of the three flags that contributes to it. I recommend you read the cited reference.
The if
statement is the actual check that you can use in your program. You can add an exception throw in there too, or even replace the if with an assert - both strategies in case you actually want the program to stop if reading file failed. When using assert you would replace the if with
assert(!file.rdstate());
and add the <cassert>
header. Assert will throw and terminate your program if the file.rdstate()
value is 0 (interpreted as false
), since you want the opposite - there is a negation upfront.
You can easily test these concepts/idea simply by specifying a non-existent file name, but I also recommend you this post for more explanation and testing ideas that will clarify the concept.