[ACCEPTED]-C faster way to check if a directory exists-opendir

Accepted answer
Score: 50

Consider using stat. S_ISDIR(s.st_mode) will tell you if it's 1 a directory.

Sample:

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

...
struct stat s;
int err = stat("/path/to/possible_dir", &s);
if(-1 == err) {
    if(ENOENT == errno) {
        /* does not exist */
    } else {
        perror("stat");
        exit(1);
    }
} else {
    if(S_ISDIR(s.st_mode)) {
        /* it's a dir */
    } else {
        /* exists but is no dir */
    }
}
...
Score: 24

You could call mkdir(). If the directory does not 3 exist then it will be created and 0 will 2 be returned. If the directory exists then 1 -1 will be returned and errno will be set to EEXIST.

Score: 20

I prefer using access()

if (0 != access("/path/to/possible_dir/", F_OK)) {
  if (ENOENT == errno) {
     // does not exist
  }
  if (ENOTDIR == errno) {
     // not a directory
  }
}

If you ensure a trailing 1 / in the directory name, this works perfectly.

Score: 3

I would use stat(), if available.

0

Score: 0

It sounds like you have a memory leak. Calling 5 opendir should not inflate the RAM of your 4 app as long as you remember to always call 3 closedir after successfully opening a directory. Also, make 2 sure you are freeing any buffers you allocated 1 to compute the directory name.

More Related questions