C fstat
Read size and type information for one file.
A simple example
fstat
- Start with A regular file containing ASCII AB
- Do this Measure its length
- Result 2 bytes
Syntax
fstat(fileno(receipt), &info)
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
./lessonRead a receipt catalog card
An archive is adding a fresh receipt to its catalog. Inspect the stored metadata to find its byte size and confirm that the entry is a regular file before recording it on the card.
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <inttypes.h>
int main(void) {
FILE *receipt = tmpfile();
if (!receipt) return 1;
struct stat info;
int ok = fputs("paid", receipt) >= 0 && fflush(receipt) == 0 &&
fstat(fileno(receipt), &info) == 0 && S_ISREG(info.st_mode);
if (ok) printf("%jd\n", (intmax_t)info.st_size);
fclose(receipt);
return ok ? 0 : 1;
}
4
The ASCII word paid has four bytes and the record is a regular file.
Prepare a gallery label
A curator stores a short UTF-8 caption beside an exhibit. Read the size field on the saved file. How many bytes did these ASCII characters occupy without a trailing newline?
Prepare a studio handover
A stage manager saves a two-word instruction for the next shift. Read the size field on the saved file. How many bytes did these ASCII characters occupy without a trailing newline?
What to watch for
These C examples use POSIX file APIs on macOS or Linux. Metadata can change between inspection and later use.