fstat() — Linux system interface
Inspect the object already referenced by a descriptor, even if its pathname was renamed or removed. Useful for verifying the opened object rather than separately checking a pathname. st_nlink is the hard-link count, not the number of descriptors; zero links can coexist with an open reference. Values can change during concurrent activity. EBADF and EOVERFLOW are possible. This operation neither consumes data nor releases the descriptor. Compile the complete C example in a fresh private working directory using gcc -std=c17 -Wall -Wextra -Wpedantic -Werror example.c -o example; run ./example. POSIX interface; tested on Linux/glibc only. These are libc-facing signatures, not raw architecture-specific syscall ABIs.
Formal Syntax & Structure
#include <sys/stat.h>int fstat(int fd, struct stat *statbuf);Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| fd | int | Valid descriptor for the object. |
| statbuf | struct stat * | Writable metadata structure. |
Return Value
0 with populated structure. On failure, returns -1 and sets errno.
Working Example
#define _DEFAULT_SOURCE#define _POSIX_C_SOURCE 200809L#include <errno.h>#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <sys/stat.h>
/* A failed check ends this short-lived demonstration. */#define CHECK(x) do { if (!(x)) { \ fprintf(stderr, "check failed at line %d: %s\n", __LINE__, #x); \ return EXIT_FAILURE; \} } while (0)
int main(void){ char path[] = "sample-XXXXXX"; int f = mkstemp(path); CHECK(f >= 0); CHECK(write(f, "x", 1) == 1); CHECK(unlink(path) == 0); struct stat s; CHECK(fstat(f, &s) == 0 && s.st_nlink == 0 && s.st_size == 1); CHECK(close(f) == 0); CHECK(fstat(f, &s) == -1 && errno == EBADF); puts("unlinked file: links=0 size=1; closed fd rejected"); return EXIT_SUCCESS;}