Library contents

C fstat

Read size and type information for one file.

A simple example

fstat

  1. Start with A regular file containing ASCII AB
  2. Do this Measure its length
  3. Result 2 bytes
Each ASCII character occupies one byte and this file has no trailing newline.

Syntax

C 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
./lesson

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

From the programint ok = fputs("paid", receipt) >= 0 && fflush(receipt) == 0 &&
Result4
lesson.c
#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;
}
Output
4

The ASCII word paid has four bytes and the record is a regular file.

Advertisements

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?

GivenFile contents “clay”
Worked result4

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?

GivenFile contents “ring bell”
Worked result9

What to watch for

These C examples use POSIX file APIs on macOS or Linux. Metadata can change between inspection and later use.

Documentation for fstat