How can I check if a directory exists?
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()");