Linux System Programming · intermediate · ~10 min
Use the four core POSIX I/O syscalls.
open(path, flags, [mode]) returns an fd or -1. read(fd, buf, n) and write(fd, buf, n) return the number of bytes transferred (which may be less than n — short reads/writes are the norm). close(fd) releases the descriptor.
Always loop short writes; always check return values; always handle EINTR (a signal interrupted the syscall — retry).
ssize_t write_all(int fd, const void *buf, size_t n) {
const char *p = buf; size_t left = n;
while (left) {
ssize_t w = write(fd, p, left);
if (w < 0) { if (errno == EINTR) continue; return -1; }
p += w; left -= (size_t)w;
}
return (ssize_t)n;
}