openat() — Linux system interface
Open a relative name starting at an already open directory; AT_FDCWD selects the current working directory. Absolute names ignore dirfd. A directory descriptor anchors lookup but does not by itself confine traversal of .. or symlinks. For hostile path resolution consider Linux openat2 with suitable restrictions, outside this example. Errors include EBADF for an invalid relative base, ENOTDIR and EACCES. Supply the variadic mode argument when O_CREAT or Linux O_TMPFILE is present, even if O_CREAT finds an existing file. Close both owned descriptors independently. 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 <fcntl.h>int openat(int dirfd, const char *path, int flags, ... /* mode_t mode */);Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| dirfd | int | Open directory descriptor or AT_FDCWD for relative names. |
| path | const char * | NUL-terminated relative or absolute pathname. |
| flags | int | Access and creation/status flags. |
| mode | mode_t | Supply mode whenever O_CREAT or O_TMPFILE is specified; otherwise it can be omitted. |
Return Value
New nonnegative descriptor. 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 <fcntl.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){ int d = open(".", O_RDONLY | O_DIRECTORY | O_CLOEXEC); CHECK(d >= 0); int f = openat(d, "sample", O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, 0600); CHECK(f >= 0); CHECK(openat(-1, "sample", O_RDONLY) == -1 && errno == EBADF); CHECK(close(f) == 0); CHECK(unlinkat(d, "sample", 0) == 0); CHECK(close(d) == 0); puts("relative open succeeded; invalid base rejected"); return EXIT_SUCCESS;}