How can I check if a directory exists?

user1543915 picture user1543915 · Sep 20, 2012 · Viewed 129.6k times · Source

How can I check if a directory exists on Linux in C?

Answer

hmjd picture hmjd · Sep 20, 2012

You can use opendir() and check if ENOENT == errno on failure:

#include <dirent.h>
#include <errno.h>

DIR* dir = opendir("mydir");
if (dir) {
    /* Directory exists. */
    closedir(dir);
} else if (ENOENT == errno) {
    /* Directory does not exist. */
} else {
    /* opendir() failed for some other reason. */
}