C fstat and stat
Distinguish regular files from directories.
A simple example
fstat and stat
- Start with A regular file a.txt
- Do this Test whether it is a directory
- Result No
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
./lessonTell 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.
#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;
}
file and folder
The upload and its enclosing workspace have different entry types.
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?
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?
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.