read() — Linux system interface
Request bytes from a descriptor into writable memory. Use the actual signed byte count, not the requested capacity, when consuming data. For a regular file, a positive-size request returning zero indicates the current end of file; for a byte-stream socket it normally indicates orderly peer shutdown. Other descriptor types can have different zero-result semantics. A zero-length request does not establish EOF and may still fail. A short read can succeed. Retry EINTR when appropriate; nonblocking EAGAIN/EWOULDBLOCK requires readiness handling instead of a tight retry loop. EBADF signals an invalid descriptor or access mode. No NUL terminator is added. The caller retains 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 <unistd.h>ssize_t read(int fd, void *buf, size_t count);Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| fd | int | Readable descriptor. |
| buf | void * | Writable buffer of at least count bytes. |
| count | size_t | Maximum byte count; keep within SSIZE_MAX. |
Return Value
Nonnegative byte count, possibly smaller than requested. Zero requires interpretation using the descriptor type and requested count. Failure returns -1 with errno set.
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){ int f = open("/dev/null", O_RDONLY); CHECK(f >= 0); char buf[8]; CHECK(read(f, buf, sizeof buf) == 0); CHECK(close(f) == 0); int q[2]; CHECK(pipe(q) == 0); CHECK(write(q[1], "abc", 3) == 3); CHECK(close(q[1]) == 0); ssize_t n = read(q[0], buf, sizeof buf); CHECK(n == 3 && memcmp(buf, "abc", 3) == 0); CHECK(read(q[0], buf, sizeof buf) == 0); CHECK(close(q[0]) == 0); printf("short read=%zd; EOF=0\n", n); return EXIT_SUCCESS;}