tags:

views:

299

answers:

3

I want to open a file for reading. However, in the context of this program, it's OK if the file doesn't exist, I just move on. I want to be able to identify when the error is "file not found" and when the error is otherwise. Otherwise means I need to quit and error.

I don't see an obvious way to do this with fstream.


I can do this with c's open and perror(). I presumed that there was a fstream way to do this as well.

+9  A: 

I don't think you can know if "the file doesn't exist". You could use is_open() for generic checking:

ofstream file(....);
if(!file.is_open())
{
  // error! myabe the file doesn't exist.
}

If you are using boost you could use boost::filesystem:

#include <boost/filesystem.hpp>
int main()
{
    boost::filesystem::path myfile("test.dat");

    if( !boost::filesystem::exists(myfile) )
    {
     // what do you want to do if the file doesn't exist 
    }
}
AraK
it is not ofstream but ifstream!
Phong
A: 

Since the result of opening a file is OS-specific, I don't think standard C++ has any way to differentiate the various types of errors. The file either opens or it doesn't.

You can try opening the file for reading, and if it doesn't open, you know it either doesn't exist or some other error happened. Then again, if you try to open it for writing afterwards and it fails, that might fall under the "something else" category.

Cogwheel - Matthew Orlando
A: 

You can use stat, which should be portable across platforms and is in the standard C library:

#include <sys/stat.h>

bool FileExists(string filename) {
    struct stat fileInfo;
    return stat(filename.c_str(), &fileInfo) == 0;
}

If stat returns 0, the file (or directory) exists, otherwise it doesn't. I assume that you'll have to have access permissions on all directories in the file's path. I haven't tested portability, but this page suggests it shouldn't be an issue.

Erik Garrison