file stream open failure reason

  • Thread starter Alexandros Frantzis
  • Start date
A

Alexandros Frantzis

Hello!
Is there a standard way to find the reason a file stream open failed (eg
file doesn't exist, access rights)?
Thanks.
 
J

Jonne Lehtinen

Alexandros said:
Hello!
Is there a standard way to find the reason a file stream open failed (eg
file doesn't exist, access rights)?
Thanks.

If using <fstream>:

#include <iostream>
#include <fstream>
int main() {

std::fstream file("non-existant-file");
if( !file ) {
std::cout << "could not open file." << std::endl;
}

return 0;

}

- Jonne Lehtinen
 
M

Mike Wahler

Alexandros Frantzis said:
Hello!
Is there a standard way to find the reason a file stream open failed (eg
file doesn't exist, access rights)?

No there is not. All you can tell is if it succeeded or
failed. Your implementation might provide extensions to
the library for determining the specific reason for
failure (many do). Check your documentation.

-Mike
 
R

Ron Natalie

Mike Wahler said:
No there is not. All you can tell is if it succeeded or
failed. Your implementation might provide extensions to
the library for determining the specific reason for
failure (many do). Check your documentation.
perror() is standard....whether it's useful or not is implementation defined.
 
R

Roger Leigh

std::fstream file("non-existant-file");
if( !file ) {
std::cout << "could not open file." << std::endl;
}

That gives absolutely no indication of the reason for the failure. If
you use open(2) or std::fopen() then it's very easy to get at the
exact reason for the failure and print an informative error message.
Under Linux, there are 17 possible error codes listed in the open(2)
manual page.

If ISO C++ can't indicate the error status properly (why not?) then
what is needed is an equivalant of fdopen(3) to turn a file descriptor
into a stream. Nicolai Josuttis has written one IIRC (fdstream).
 
M

Mike Wahler

Ron Natalie said:
perror() is standard....
Right.

whether it's useful or not is implementation defined.

Agreed. So yes, there is a "standard way", but the
*results* will not be "standard". That's what I was
trying to say, albeit not very well. :)

-Mike
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,161
Messages
2,570,892
Members
47,426
Latest member
MrMet

Latest Threads

Top