write() — Linux system interface
Transfer bytes from a readable buffer to a writable descriptor. Advance by the number actually transferred, retry EINTR, and stop on other errors or unexpected zero progress. EAGAIN on nonblocking I/O calls for readiness handling. EPIPE can be accompanied by SIGPIPE on a broken pipe. ENOSPC and EIO can occur even after earlier successful writes. Success is not a durability guarantee; use appropriate synchronization and check close errors. This bounded regular-file example checks its round trip; it does not force a partial write. 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 <unistd.h>ssize_t write(int fd, const void *buf, size_t count);Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| fd | int | Writable descriptor. |
| buf | const void * | Source buffer of at least count bytes. |
| count | size_t | Maximum bytes to transfer; keep within SSIZE_MAX. |
Return Value
Actual bytes written, possibly less than count. 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>#include <string.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(unlink(path) == 0); const char data[] = "hello"; size_t done = 0; while (done < sizeof data - 1) { ssize_t n = write(f, data + done, sizeof data - 1 - done); if (n < 0 && errno == EINTR) continue; CHECK(n > 0); done += (size_t)n; } CHECK(lseek(f, 0, SEEK_SET) == 0); char buf[5]; CHECK(read(f, buf, sizeof buf) == (ssize_t)sizeof buf); CHECK(memcmp(buf, data, sizeof buf) == 0); CHECK(write(-1, data, 1) == -1 && errno == EBADF); CHECK(close(f) == 0); printf("wrote %zu bytes; verified; EBADF confirmed\n", done); return EXIT_SUCCESS;}