tags:

views:

283

answers:

2

Is there any way to get a specific error condition when a C++ stream open fails? That is, whether it failed because the file didn't exist, or permissions were wrong, or etc. Basically I'm looking for functionality equivalent to errno for fopen() in plain C.

GCC seems to set errno properly, but that doesn't seem to be required by the C++ standard and I can't determine whether this is just an artifact of the way they implemented streams, or a deliberate feature (and thus I don't know whether it will persist across versions).

Is there a way to get this info reliably, either in standard C++ or non-accidentally in one or more major compilers?

A: 

In Visual Studio fopen and the like set the last-error code value. It can be retrieved with GetLastError(). The result will be one of these values.

Gordon Wilson
Do you have any link to where this is laid out in the VS doc? I have been looking at the stream pages on MSDN but I can't find any mention of this behaviour. I'm not saying it doesn't work like this but it would be good to see some official doc.
Rodion Ingles
I don't think it is laid out in the VS docs. Or perhaps my google-foo is just too weak. However I did find several forums posts backing up my recollection that fopen and the like are all wrappers around their equivalent winapi functions. So fopen is actually calling CreateFile, which sets the error code.Regardless, a quick test should bear it out (at least for the easy to simulate file errors). I would do it myself and post the results. But, alas, I don't have easy access to visual studio at the moment.
Gordon Wilson
+2  A: 

You can look at the ios flags (badbit, eofbit, failbit, goodbit) for general reasons. Testing will is easier using ios::bad(), ios::fail(), ios::eof(), or ios::good(). The stream can also be set to generate exceptions on error, using ios::exceptions().

Detailed I/O Error Reporting may be available in some implementations, as you point out for GCC. You may have to rely on this behavior for the different compilers. If there is a chance for multiple compilers, make sure to test and probably include preprocessor statements to check the current compiler, etc.
As far as I know, the only other place it's discussed is in proposed TR2 additions.

Kris Kumler