Lesson 2 of 5
POSIX File Descriptors - open, read, write & close
POSIX file I/O (`open`/`read`/`write`/`close`) operates on **file descriptors** - small integers representing open files. Unlike `fopen`/`fclose` which buffer I/O in `FILE` structs, POSIX I/O is **unbuffered** and closer to the OS. Understanding the difference: when to use which, what file descriptors 0/1/2 are, and how `read` may return less than requested.
POSIX I/O - open/read/write vs stdio - When to Use Which
/* posix_io.c - POSIX file descriptor I/O */
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h> /* open, O_RDONLY, O_WRONLY, O_CREAT */
#include <unistd.h> /* read, write, close */
#include <sys/stat.h> /* file permission bits S_IRUSR etc. */
#include <errno.h>
#define BUF_SIZE 4096
/* ── open - returns file descriptor (int) or -1 on error ──── */
int copy_file(const char *src, const char *dst) {
/* Open source for reading */
int fd_in = open(src, O_RDONLY);
if (fd_in < 0) {
perror("open src");
return -1;
}
/* Open destination for writing - create or truncate
O_WRONLY | O_CREAT | O_TRUNC, permissions = rw-r--r-- */
int fd_out = open(dst,
O_WRONLY | O_CREAT | O_TRUNC,
S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
if (fd_out < 0) {
perror("open dst");
close(fd_in);
return -1;
}
char buf[BUF_SIZE];
ssize_t nread;
/* ── read loop - MUST loop: read may return LESS than BUF_SIZE ── */
while ((nread = read(fd_in, buf, sizeof(buf))) > 0) {
/* write loop - write may also return less (EINTR / partial) */
ssize_t total_written = 0;
while (total_written < nread) {
ssize_t nw = write(fd_out, buf + total_written,
(size_t)(nread - total_written));
if (nw < 0) {
if (errno == EINTR) continue; /* interrupted - retry */
perror("write");
close(fd_in);
close(fd_out);
return -1;
}
total_written += nw;
}
}
if (nread < 0) { perror("read"); }
close(fd_in);
close(fd_out);
return nread < 0 ? -1 : 0;
}
/* ── stdio vs POSIX I/O - when to use which ─────────────────
FILE* / fread / fwrite / fgets:
+ Buffered: fewer syscalls, faster for many small reads
+ Portable: works on Windows, Linux, macOS
+ Formatted I/O: fprintf, fscanf
- Cannot be used with select/poll (file descriptors needed)
- No access to raw file descriptor flags
POSIX open/read/write:
+ Direct syscall interface - precise control
+ Non-blocking I/O: O_NONBLOCK flag
+ Works with select/poll/epoll for I/O multiplexing
+ Access to file descriptor-based features (socket, pipe)
- Unbuffered: need to implement own buffering for small reads
- Not portable to non-POSIX (Windows)
Rule: Use FILE* for file processing.
Use file descriptors for sockets, pipes, select/poll.
Never mix fd and FILE* for the same file. */
/* ── Standard file descriptors (always open) ─────────────────
0 = stdin (STDIN_FILENO) - read keyboard
1 = stdout (STDOUT_FILENO) - write terminal
2 = stderr (STDERR_FILENO) - write errors
write(STDOUT_FILENO, "hi
", 3) == printf("hi
") */
int main(int argc, char **argv) {
if (argc != 3) {
fprintf(stderr, "Usage: %s <src> <dst>
", argv[0]);
return 1;
}
if (copy_file(argv[1], argv[2]) != 0) return 1;
printf("Copied: %s → %s
", argv[1], argv[2]);
return 0;
}
/* Build: gcc -Wall -Wextra -std=c99 posix_io.c -o fcopy
Run: ./fcopy /etc/hostname /tmp/hostname_copy */Common Mistakes
- `read` can return less than requested - a single `read(fd, buf, 100)` may return 1-100. Always loop until you have all the data you need or detect EOF (return 0) or error (return -1).
- Not handling `EINTR` - on systems with signals, `read`/`write` can be interrupted with errno EINTR. Always check: `if (nr < 0 && errno == EINTR) continue;` in the read/write loop.
- Mixing `FILE*` and file descriptor for the same file - `fopen` creates buffers; then using `read(fileno(fp), ...)` bypasses those buffers. You'll miss data or duplicate reads. Choose one or the other.
Tip
Tip
Practice POSIX File Descriptors open read write close in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Low-level system calls interact directly with OS file descriptor tables without user-space buffering
Practice Task
Note
Practice Task - (1) Write a working example of POSIX File Descriptors open read write close from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with POSIX File Descriptors open read write close is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready c code.
Key Takeaways
- POSIX file I/O (`open`/`read`/`write`/`close`) operates on **file descriptors** - small integers representing open files.
- `read` can return less than requested - a single `read(fd, buf, 100)` may return 1-100. Always loop until you have all the data you need or detect EOF (return 0) or error (return -1).
- Not handling `EINTR` - on systems with signals, `read`/`write` can be interrupted with errno EINTR. Always check: `if (nr < 0 && errno == EINTR) continue;` in the read/write loop.
- Mixing `FILE*` and file descriptor for the same file - `fopen` creates buffers; then using `read(fileno(fp), ...)` bypasses those buffers. You'll miss data or duplicate reads. Choose one or the other.
Finished this lesson?