68

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.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Paul Nathan
  • 39,638
  • 28
  • 112
  • 212

10 Answers10

94

EDIT: I've been notified that this does not necessarily indicate a file does not exist, as it may be flagged due to access permissions or other issues as well.

I know I'm extremely late in answering this, but I figured I'd leave a comment anyway for anyone browsing. You can use ifstream's fail indicator to tell if a file exists.

ifstream myFile("filename.txt");
    if(myFile.fail()){
        //File does not exist code here
    }
//otherwise, file exists
SwarthyMantooth
  • 1,799
  • 1
  • 15
  • 27
  • 6
    What you suggest is NOT a way to check for "file not found". `fail()` does not indicate "file does not exist", it just indicates "something is wrong". In your particular example it can be "access denied" or "sharing violation" etc. – PowerGamer Jan 05 '15 at 12:18
  • 1
    Very good point, I didn't even consider that. I'll modify the response so that people are aware. – SwarthyMantooth Jan 13 '15 at 17:41
46

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! maybe 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 
    }
}
Khaled Alshaya
  • 94,250
  • 39
  • 176
  • 234
  • 8
    it is not ofstream but ifstream! – Phong Oct 15 '10 at 05:30
  • Note that both ways check something else: the file may well be there but you might not have the necessary permissions... – rubenvb Oct 24 '13 at 15:00
  • 9
    Isn't this an inherently racy solution? – Simon Lindgren Apr 15 '14 at 09:03
  • 1
    From [this](http://stackoverflow.com/questions/12774207/fastest-way-to-check-if-a-file-exist-using-standard-c-c11-c) thread, there's also the `file.good()` option, which I think is more appropriate here. – Dan Dec 12 '16 at 23:32
  • `boost::filesystem::exists` has been added in C++17 as [`std::filesystem::exists`](http://en.cppreference.com/w/cpp/filesystem/exists). – Zitrax Dec 14 '16 at 08:54
25

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 (ifstream::is_open() returns false), 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.

ZenjieLi
  • 161
  • 1
  • 5
Cogwheel
  • 22,781
  • 4
  • 49
  • 67
9

A simple way from http://www.cplusplus.com/forum/general/1796/

ifstream ifile(filename);
if (ifile) {
  // The file exists, and is open for input
}
LI Xuhong
  • 2,339
  • 2
  • 17
  • 32
  • 2
    in case anyone else is wondering: [According to the documentation](https://en.cppreference.com/w/cpp/io/basic_ifstream), this is identical to `!ifile.fail()`. `if(!ifile)` is equivalent to `ifile.fail()`. – Zoe Aug 29 '19 at 15:18
5

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
  • 1,697
  • 1
  • 14
  • 13
  • Should explictly check return code, as it may be non-zero for reasons other than file doesn't exist. See http://pubs.opengroup.org/onlinepubs/009695399/functions/stat.html – gerardw Oct 11 '13 at 12:04
  • 5
    This is a WRONG thing to do, because during the time AFTER stat() returned and BEFORE `fstream`'s open() got to actually opening a file the file may have been already gone (deleted by another process in the system). – PowerGamer Jan 05 '15 at 12:11
  • http://stackoverflow.com/questions/12774207/fastest-way-to-check-if-a-file-exist-using-standard-c-c11-c – Ethan Feb 16 '16 at 03:30
2

A better way:

std::ifstream stream;
stream.exceptions(std::ifstream::failbit | std::ifstream::badbit);
stream.open(fileName, std::ios::binary);
user1633272
  • 2,007
  • 5
  • 25
  • 48
  • 2
    Please add some explaination/[references](https://en.cppreference.com/w/cpp/io/basic_ios/exceptions). – helmesjo Nov 05 '18 at 07:41
0

With C++17 you can use std::filesystem::exists.

Antonio
  • 19,451
  • 13
  • 99
  • 197
0
if (!fs::exists(fileName))
{
     // error! file doesn't exist.
}
hunght
  • 1
-1

Let's me give example with real running:

  1. file does't exist:

enter image description here

  1. file exist:

enter image description here

see http://www.cplusplus.com/reference/fstream/ifstream/ for more information about its public function.

Jayhello
  • 5,931
  • 3
  • 49
  • 56
  • 1
    This doesn't account for the possibility that the file actually exists but there is an error in accessing it, like permission denied, I/O errors, etc – Remy Lebeau Dec 08 '18 at 03:29
-6

Straight way without creating ifstream object.

if (!std::ifstream(filename))
{
     // error! file doesn't exist.
}
Arun
  • 2,247
  • 3
  • 28
  • 51