C faster way to check if a directory exists

69,281

Solution 1

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

Solution 2

Consider using stat. S_ISDIR(s.st_mode) will tell you if it's 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 */
    }
}
...

Solution 3

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 / in the directory name, this works perfectly.

Solution 4

I would use stat(), if available.

Share:
69,281
Frederico Schardong
Author by

Frederico Schardong

Updated on July 09, 2022

Comments

  • Frederico Schardong
    Frederico Schardong almost 2 years

    I'm using opendir function to check if a directory exists. The problem is that I'm using it on a massive loop and it's inflating the ram used by my app.

    What is the best (fastest) way to check if a directory exists in C? What is the best (fastest) way to create it if doesn't exists?