File Handling · intermediate · ~10 min

File permissions and stat

Inspect file metadata with stat.

Lesson

int stat(const char *path, struct stat *out) fills a struct with size, type (regular/dir/symlink), mtime, and POSIX permission bits.

Use it before opening to validate ownership or mode; combine with S_IRUSR, S_IWOTH, etc. masks.

Code examples

struct stat st;
if (stat(path, &st) == 0) {
    if (S_ISREG(st.st_mode)) printf("regular file\n");
    if (st.st_mode & S_IWOTH) printf("WORLD-WRITABLE!\n");
}

Common mistakes

  • Confusing stat (follows symlinks) with lstat (doesn't).