Library contents

C fstat and stat

Distinguish regular files from directories.

A simple example

fstat and stat

  1. Start with A regular file a.txt
  2. Do this Test whether it is a directory
  3. Result No
A regular file and a directory have different entry types.

Syntax

C syntax
S_ISREG(info.st_mode)
Run these examples in C

Save one example at a time as lesson.c. Use C17 on macOS or Linux with a POSIX shell.

cc -std=c17 -Wall -Wextra lesson.c -lm -o lesson
./lesson

Tell an uploaded file apart from its folder

A registration desk receives documents through an upload folder. The clerk needs to confirm that the submitted entry is a regular file and that the enclosing location is a directory before processing the batch.

From the programchar upload[] = "/tmp/registration-XXXXXX"
Resultfile and folder
lesson.c
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>

int main(void) {
    char upload[] = "/tmp/registration-XXXXXX";
    int fd = mkstemp(upload);
    if (fd == -1) return 1;
    struct stat file, folder;
    int ok = fstat(fd, &file) == 0 && stat("/tmp", &folder) == 0;
    close(fd);
    unlink(upload);
    if (!ok) return 1;
    if (S_ISREG(file.st_mode) && S_ISDIR(folder.st_mode)) puts("file and folder");
    return 0;
}
Output
file and folder

The upload and its enclosing workspace have different entry types.

Advertisements

Locate a rehearsal score

The choir stores each score inside a season folder. A clerk creates an ordinary file at the given location. Which entry type should the status check report?

Givenspring / alto.txt
Worked resultRegular file

Locate a workshop handout

An instructor stores the current template in a class folder. A clerk creates an ordinary file at the given location. Which entry type should the status check report?

Givenceramics / glaze.pdf
Worked resultRegular file

What to watch for

These C examples use POSIX file APIs on macOS or Linux. Status checks describe the instant of inspection. Handle failure at the subsequent open.

Documentation for fstat and stat