open() — Linux system interface
Open a pathname and obtain a new descriptor referring to an open file description. Choose exactly one access mode; combine additional flags with |. Supply mode whenever O_CREAT or O_TMPFILE requires it; umask can remove permission bits. O_EXCL with O_CREAT rejects an existing name; avoid accidental O_TRUNC. O_CLOEXEC prevents unintended inheritance through successful exec. Test the returned descriptor, not errno after success. Common failures: ENOENT, EACCES, EEXIST, EMFILE. The caller owns the returned descriptor and closes it once. 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 open(const char *path, int flags, ... /* mode_t mode */);Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| path | const char * | NUL-terminated pathname. |
| flags | int | Access mode and additional flags. |
| mode | mode_t | Required with O_CREAT or O_TMPFILE; creation permission bits. |
Return Value
Nonnegative descriptor 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 <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 f = open("sample", O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, 0600); CHECK(f >= 0); int flags = fcntl(f, F_GETFD); CHECK(flags >= 0 && (flags & FD_CLOEXEC)); CHECK(open("sample", O_WRONLY | O_CREAT | O_EXCL, 0600) == -1 && errno == EEXIST); CHECK(close(f) == 0); CHECK(unlink("sample") == 0); puts("created exclusively; CLOEXEC set; EEXIST confirmed"); return EXIT_SUCCESS;}