Coder Perfect

What is the best way to see if a directory exists?


In C, how do I see if a directory exists on Linux?

Asked by user1543915

Solution #1

On failure, you can use opendir() to see if ENOENT == errno:

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

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

Answered by hmjd

Solution #2

To see if a folder exists, use the code below. It is compatible with both Windows and Linux operating systems.

#include <stdio.h>
#include <sys/stat.h>

int main(int argc, char* argv[])
    const char* folder;
    //folder = "C:\\Users\\SaMaN\\Desktop\\Ppln";
    folder = "/tmp";
    struct stat sb;

    if (stat(folder, &sb) == 0 && S_ISDIR(sb.st_mode)) {
    } else {

Answered by Saman

Solution #3

You could use stat() and feed it the address of a struct stat, then check for S IFDIR in the st mode member.

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


char d[] = "mydir";

struct stat s = {0};

if (!stat(d, &s))
  printf("'%s' is %sa directory.\n", d, (s.st_mode & S_IFDIR)  : "" ? "not ");
  // (s.st_mode & S_IFDIR) can be replaced with S_ISDIR(s.st_mode)

Answered by alk

Solution #4

Attempting to open it, for example with opendir(), is definitely the best option.

Rather than checking and then trying, it’s always better to try to utilize a filesystem resource and handle any issues that arise because it doesn’t exist. In the latter technique, there is a clear race condition.

Answered by unwind

Solution #5

The S ISDIR macro can be used on the st mode field, according to man(2)stat:

bool isdir = S_ISDIR(st.st_mode);

If your product can run on other OSs, I would advocate using Boost and/or Qt4 to make cross-platform compatibility easier.

Answered by TheFriendlyDragon

Post is based on