On Tuesday, 23 January 2018 22:54:20 UTC+2, Gert-Jan de Vos wrote:
> Whenever I use fstream for file IO, I have to look up the details on
> how to detect IO errors like file not found, access violation or disk
> full. Sometimes I need to check failbit or badbit, sometimes only
> badbit and I can't remember when to choose what.
Just use ios::fail() to check if one of those is set and look
up actual cause from errno:
std::ifstream f;
f.open(fileName);
if (f.fail())
{
std::cout << "Error: " << strerror(errno) << '\n';
}
The errno is thread-local since C++11 (that added threads
into C++) so it works fine in multi-threaded app as well.
> Ideally I would like to get exceptions with the OS error details
> included as proposed in N2503. Unfortunately with MSVC2017
> I just get "iostream error" in the exception object.
Same there, e.what() tells some vague nonsense not worth reading
and errno is lot better source of information:
std::ifstream f;
std::ios_base::iostate exceptionMask = f.exceptions() | std::ios::failbit;
f.exceptions(exceptionMask);
try
{
f.open(fileName);
}
catch (std::ios_base::failure& e)
{
std::cout << "Vague whine: " << e.what() << '\n';
std::cout << "Error: " << strerror(errno) << '\n';
}
IOW ... TL;DR it is rare case where errno is not sufficient for
diagnosing fstream i/o issues.