How can I check if a directory exists on Linux in C?
In order to check if a directory exists in Bash using shorter forms, specify the “-d” option in brackets and append the command that you want to run if it succeeds. [[ -d <directory> ]] && echo "This directory exists!" [ -d <directory> ] && echo "This directory exists!"
mkdir indeed emits an error if the directory exists, unless using the -p flag. in error, you could check for the code like this if(err. code == 'EEXIST') this condition will get true if the directory already exists.
os. path. isdir() method in Python is used to check whether the specified path is an existing directory or not. This method follows a symbolic link, which means if the specified path is a symbolic link pointing to a directory then the method will return True.
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. */ }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With