Check if a path is a directory with stat and S_ISDIR
Check whether a path is a directory with stat and the S_ISDIR macro on Linux 6.12, and know when lstat gives a different answer for a symlink.
stat fills a struct stat, and S_ISDIR(st.st_mode) tests the file type inside st_mode. Do not mask and compare the bits yourself: the type shares the field with the permission bits, and the macro hides the layout. A missing path makes stat return -1, so the function has three outcomes, not two: directory, something else, and an error. See POSIX sys/stat.h.
#include <stdio.h>
#include <sys/stat.h>
static void check(const char *path) {
struct stat st;
if (stat(path, &st) < 0)
printf("%s: cannot stat\n", path);
else
printf("%s: %s\n", path, S_ISDIR(st.st_mode) ? "directory" : "not a directory");
}
int main(void) {
check("/tmp");
check("/etc/passwd");
check("/no/such/path");
return 0;
}/tmp: directory
/etc/passwd: not a directory
/no/such/path: cannot statstat follows symbolic links, so a link to a directory counts as a directory. lstat looks at the link itself and reports a symlink, which is what you want when you are about to delete or walk a tree and must not follow a link out of it.
Between the check and whatever comes next, the path can change, so the answer is a hint. If you intend to open the directory, open it with O_DIRECTORY and test the result, which fails with ENOTDIR on anything else. That removes the race.