stat() — Linux system interface
Inspect metadata by pathname. The final symlink is followed; use lstat for the link itself. st_mode combines type and permission bits, st_size is logical size for regular files, and st_dev plus st_ino identify a file object within the relevant filesystem context. Path traversal requires directory search permission. Metadata can change concurrently; stat then open is not a security guarantee. Errors include ENOENT, EACCES, ELOOP and EOVERFLOW. No descriptor is acquired. 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 stat(const char *restrict path, struct stat *restrict statbuf);Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| path | const char * | NUL-terminated pathname. |
| statbuf | struct stat * | Writable metadata structure. |
Return Value
0 with populated structure on success. 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>#include <inttypes.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, "abc", 3) == 3); CHECK(close(f) == 0); struct stat s; CHECK(stat(path, &s) == 0); CHECK(S_ISREG(s.st_mode) && s.st_size == 3); printf("regular file; size=%jd\n", (intmax_t)s.st_size); CHECK(unlink(path) == 0); CHECK(stat(path, &s) == -1 && errno == ENOENT); puts("removed name: ENOENT"); return EXIT_SUCCESS;}