tags:

views:

647

answers:

2

Hello,

Seems like this should be simple, but I don't find it in a net search.

I have an ofstream which is open() and fail() is now true, I'd like to know the reason for the failure to open, like with errno I would do sys_errlist[errno].

Thanks.

-William

+2  A: 

The strerror function from <cstring> might be useful. This isn't necessarily standard or portable, but it works okay for me using GCC on an Ubuntu box:

#include <iostream>
using std::cout;
#include <fstream>
using std::ofstream;
#include <cstring>
using std::strerror;
#include <cerrno>

int main() {

  ofstream fout("read-only.txt");  // file exists and is read-only
  if( !fout ) {
    cout << strerror(errno) << '\n'; // displays "Permission denied"
  }

}
Nate Kohl
That might well work, and strerror() is a standard C++ function. Unfortunately, the standard does not state that open() sets errno, so you can't absolutely depend on it.
anon
+3  A: 

Unfortunately, there is no standard way of finding out exactly why open() failed. Note that sys_errlist is not standard C++ (or Standard C, I believe).

anon