Skip to content
systemcoding.dev
Systems Programming

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.

1 min read
Summarize in AI

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.

isdir.cc
#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;
}
Text
/tmp: directory
/etc/passwd: not a directory
/no/such/path: cannot stat

stat 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.

Taggedcposix
Share

More snippets

Systems Programming

Get the page size with sysconf(_SC_PAGESIZE)

Read the memory page size at run time with sysconf(_SC_PAGESIZE) instead of hard-coding 4096, which is wrong on arm64 kernels built with 16K or 64K pages.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.