Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Fast way to test for existence of a file in C++?

  1. Mar 10, 2005 #1

    ahrkron

    User Avatar
    Staff Emeritus
    Gold Member

    Here's the situation:

    I'm running over a few thousand files, some of which may have already been processed. In order to decide if a file has to be processed, I check if the corresponding output file exists.

    The problem:

    I tried using FILE *f = fopen(<filename>,"r"), and test for f!=0; however, it takes a long time to just open the files.

    Any suggestions?

    Edit: FILE instead of TFILE.
     
    Last edited: Mar 10, 2005
  2. jcsd
  3. Mar 10, 2005 #2

    dduardo

    User Avatar
    Staff Emeritus

    How about this:

    Code (Text):

    #include <sys/stat.h>

    int fexist( char *filename ) {
      struct stat buffer ;
      if ( stat( filename, &buffer ) ) return 1 ;
      return 0 ;
    }
     
    This is under Unix, so stat.h may not be under sys/ for windows.
     
  4. Mar 10, 2005 #3
    If you're programming for Windows check if the following works:

    Code (Text):

    System::IO::File::Exists(file);
     
    which returns true if the file exists, false otherwise.
     
    Last edited: Mar 10, 2005
  5. Mar 10, 2005 #4

    dduardo

    User Avatar
    Staff Emeritus

  6. Mar 10, 2005 #5

    ahrkron

    User Avatar
    Staff Emeritus
    Gold Member

    Thanks!

    That is fast enough.
    Just it seems to have the logic reversed: stats(...) returns -1 for non-existing files and 0 for existing files.

    (or it may be my expectation of 1 to mean "true" and 0 to be "does not exist").
     
  7. Mar 10, 2005 #6

    ahrkron

    User Avatar
    Staff Emeritus
    Gold Member

    OK. I was just being dumb. I had a piece of code before the actual test of file existence that was using some serious IO. Now both versions (dduardo's and my original FILE use) work ok.

    Thanks anyway!
     
  8. Mar 10, 2005 #7
    But you code you provided will work with Microsoft's compiler.
     
  9. Oct 8, 2011 #8
    You also have the posix

    #include <unistd.h>
    int access(const char *path, int amode);

    Not sure it works on *dows, though
     
  10. Oct 8, 2011 #9

    jtbell

    User Avatar

    Staff: Mentor

    Um... did you notice that the posts you responded to are six and a half years old? :smile:
     
  11. Oct 8, 2011 #10
    That only makes it only more important to check if the file still exists.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?



Similar Discussions: Fast way to test for existence of a file in C++?
  1. C++ file i/o (Replies: 7)

  2. C++ csv file reading (Replies: 2)

Loading...