How can I check if a directory exists on Linux in C?
6 Answers
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. */
}
Use the following code to check if a folder exists. It works on both Windows & Linux platforms.
#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)) {
printf("YES\n");
} else {
printf("NO\n");
}
}
You might use stat()
and pass it the address of a struct stat
, then check its member st_mode
for having S_IFDIR
set.
#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)
else
perror("stat()");
The best way is probably trying to open it, using just opendir()
for instance.
Note that it's always best to try to use a filesystem resource, and handling any errors occuring because it doesn't exist, rather than just checking and then later trying. There is an obvious race condition in the latter approach.
According to man(2)stat you can use the S_ISDIR macro on the st_mode field:
bool isdir = S_ISDIR(st.st_mode);
Side note, I would recommend using Boost and/or Qt4 to make cross-platform support easier if your software can be viable on other OSs.
You may also use access
in combination with opendir
to determine if the directory exists, and, if the name exists, but is not a directory. For example:
#include <sys/stat.h>
#include <dirent.h>
#include <unistd.h>
/* test that dir exists (1 success, -1 does not exist, -2 not dir) */
int
xis_dir (const char *d)
{
DIR *dirptr;
if (access ( d, F_OK ) != -1 ) {
// file exists
if ((dirptr = opendir (d)) != NULL) {
closedir (dirptr); /* d exists and is a directory */
} else {
return -2; /* d exists but is not a directory */
}
} else {
return -1; /* d does not exist */
}
return 1;
}