Based on The Linux Programming Interface Chapter 4 (File I/O: The Universal I/O Model) and Chapter 5 (File I/O: Further Details).
See Go io package for equivalent abstractions (io.Reader, io.Writer, io.Seeker) in Go.
Core Function Signatures#
All I/O operations on regular files, devices, pipes, sockets, and terminals use these core system calls.
1. open#
Opens an existing file or creates a new file.
#include <fcntl.h>
int open(const char *pathname, int flags, ... /* mode_t mode */);- Return: New file descriptor (non-negative integer) on success;
-1on error (errnoset) - Parameters:
<pathname>: Path to the target file<flags>: Bitwise OR of access mode and status flags<mode>: Permissions for newly created file (0644,0600, etc.), required only whenO_CREATis specified
Access Modes (Specify exactly one)#
O_RDONLY: Open for read-onlyO_WRONLY: Open for write-onlyO_RDWR: Open for reading and writing
Common Creation and Status Flags#
O_CREAT: Create file if it does not existO_EXCL: Used withO_CREAT; fail atomically if file already exists (EEXIST). Prevents Time-of-Check to Time-of-Use (TOCTOU) race conditions when creating lock files (app.lock)O_TRUNC: Truncate existing file length to zeroO_APPEND: Atomically updates file offset to end of file before each write. Prevents race conditions between multiple processes appending to the same file (eliminateslseek(SEEK_END)race conditions)O_NONBLOCK: Open in non-blocking mode (useful for FIFOs, pipes, and sockets)O_CLOEXEC: Enable close-on-exec flag atomically. Prevents file descriptor leakage acrossexeccalls to child programs (stored in the process-private FD table)
2. read#
Reads data from an open file descriptor into a memory buffer.
#include <unistd.h>
ssize_t read(int fd, void *buffer, size_t count);- Return:
> 0: Number of bytes actually read0: End-of-File (EOF) reached-1: Error occurred (errnoset)
- Parameters:
<fd>: Open file descriptor<buffer>: Destination memory address in RAM<count>: Maximum number of bytes to read
3. write#
Writes data from a memory buffer to an open file descriptor.
#include <unistd.h>
ssize_t write(int fd, const void *buffer, size_t count);- Return: Number of bytes actually written on success;
-1on error (errnoset) - Parameters:
<fd>: Open file descriptor<buffer>: Source memory address in RAM<count>: Number of bytes to write
4. close#
Closes an open file descriptor, releasing the descriptor back to the process pool.
#include <unistd.h>
int close(int fd);- Return:
0on success;-1on error (errnoset) - Parameters:
<fd>: Open file descriptor to release
5. lseek#
Repositions the read/write file offset of an open file descriptor.
#include <unistd.h>
off_t lseek(int fd, off_t offset, int whence);- Return: Resulting file offset from beginning of file on success;
(off_t) -1on error (errnoset) - Parameters:
<fd>: Open file descriptor<offset>: Byte displacement relative to<whence><whence>: Reference position for offset calculation
Directives (whence)#
SEEK_SET: Offset is set relative to the start of the fileSEEK_CUR: Offset is set relative to the current file positionSEEK_END: Offset is set relative to the end of the file (EOF)
Standard File Descriptors#
| Descriptor | Macro | Stream |
|---|---|---|
0 | STDIN_FILENO | Standard Input (stdin) |
1 | STDOUT_FILENO | Standard Output (stdout) |
2 | STDERR_FILENO | Standard Error (stderr) |
Common I/O Patterns#
1. Sequential Read & Write Loop (System Utility Pattern)#
Streams data chunk by chunk from a file descriptor to standard output without requiring a null terminator.
#define BUF_SIZE 4096
char buffer[BUF_SIZE];
ssize_t num_read;
while ((num_read = read(src_fd, buffer, BUF_SIZE)) > 0) {
if (write(STDOUT_FILENO, buffer, num_read) != num_read) {
perror("write failed");
break;
}
}
if (num_read == -1) {
perror("read failed");
}2. Read with Null-Terminated C String (String Processing Pattern)#
Leaves 1 byte in the buffer for the null terminator \0 to safely process data with string functions like printf.
#define BUF_SIZE 4096
char buffer[BUF_SIZE];
ssize_t num_read;
while ((num_read = read(src_fd, buffer, sizeof(buffer) - 1)) > 0) {
buffer[num_read] = '\0';
printf("%s", buffer);
}
if (num_read == -1) {
perror("read failed");
}Kernel Data Structures & File Sharing (TLPI Ch 5)#
The Linux kernel maintains three distinct data structures to manage open files (TLPI Figure 5-2).
graph LR
subgraph "Process A"
FDA1["FD 1 (stdout)"]
FDA20["FD 20 (dup of 1)"]
FDA2["FD 2 (stderr)"]
FDA0["FD 0"]
end
subgraph "Process B"
FDB2["FD 2 (fork from A)"]
FDB3["FD 3"]
end
subgraph "Open File Table (System-Wide)"
OFT1["Open File Description 1<br/>• File Offset: 0<br/>• Flags: O_WRONLY<br/>• Ref Count: 2"]
OFT2["Open File Description 2<br/>• File Offset: 250<br/>• Flags: O_RDWR<br/>• Ref Count: 2"]
OFT3["Open File Description 3<br/>• File Offset: 0<br/>• Flags: O_RDONLY<br/>• Ref Count: 1"]
OFT4["Open File Description 4<br/>• File Offset: 100<br/>• Flags: O_RDONLY<br/>• Ref Count: 1"]
end
subgraph "i-node Table (System-Wide)"
INODE1["i-node: results.log"]
INODE2["i-node: terminal / pipe"]
INODE3["i-node: file.txt"]
end
FDA1 -->|dup| OFT1
FDA20 -->|dup| OFT1
FDA2 -->|fork| OFT2
FDB2 -->|fork| OFT2
FDA0 -->|open| OFT3
FDB3 -->|open| OFT4
OFT1 --> INODE1
OFT2 --> INODE2
OFT3 --> INODE3
OFT4 --> INODE3
File Offset Sharing Rules#
| Creation Method | Target Structure | Offset Sharing |
|---|---|---|
dup() / dup2() | Refers to the same Open File Description within the same process | Shared (reads/writes in one FD advance the offset for both) |
fork() | Child process inherits FD table pointing to the same Open File Description | Shared (parent and child share file offsets) |
Separate open() calls | Each call allocates an independent Open File Description | Independent (each descriptor maintains its own offset even on the same i-node) |
File Descriptor Duplication (dup, dup2)#
Duplicates an existing file descriptor by copying its pointer in the process FD table to a new entry.
#include <unistd.h>
int dup(int oldfd);
int dup2(int oldfd, int newfd);dup(oldfd): Allocates the lowest unused file descriptor number and copiesoldfd’s pointer into it.dup2(oldfd, newfd): Atomically closesnewfd(if already open) and copiesoldfd’s pointer intonewfd. Returnsnewfd.
Standard Output Redirection Idiom (ls > output.txt)#
int file_fd = open("output.txt", O_CREAT | O_WRONLY | O_TRUNC, 0644);
if (file_fd == -1) {
perror("open");
}
// Redirect stdout (1) to output.txt
if (dup2(file_fd, STDOUT_FILENO) == -1) {
perror("dup2");
}
// Close original descriptor to avoid FD leaks
close(file_fd);
// Subsequent printf() and write(1, ...) output will go to output.txt
printf("This message is written to output.txt\n");File Control (fcntl)#
Queries and modifies flags and attributes of an already open file descriptor dynamically.
#include <fcntl.h>
int fcntl(int fd, int cmd, ... /* arg */);Dynamic Non-Blocking Mode Idiom (O_NONBLOCK)#
// 1. Fetch current file status flags
int flags = fcntl(fd, F_GETFL);
if (flags == -1) {
perror("fcntl F_GETFL");
}
// 2. Enable O_NONBLOCK bit
flags |= O_NONBLOCK;
// 3. Apply updated flags back to the kernel
if (fcntl(fd, F_SETFL, flags) == -1) {
perror("fcntl F_SETFL");
}Advanced I/O#
1. Thread-Safe Positional I/O (pread, pwrite)#
Performs I/O at a specified offset without altering the current file offset in the Open File Description.
#include <unistd.h>
ssize_t pread(int fd, void *buf, size_t count, off_t offset);
ssize_t pwrite(int fd, const void *buf, size_t count, off_t offset);- Atomically combines seek and read/write operations into a single system call.
- Safe for concurrent multi-threaded access on a shared file descriptor without mutex synchronization.
2. Scatter-Gather I/O (readv, writev)#
Transfers data between a single file descriptor and multiple non-contiguous memory buffers in a single system call.
#include <sys/uio.h>
struct iovec {
void *iov_base; // Starting address of buffer
size_t iov_len; // Length of buffer in bytes
};
ssize_t readv(int fd, const struct iovec *iov, int iovcnt);
ssize_t writev(int fd, const struct iovec *iov, int iovcnt);Atomic Multi-Buffer Write Pattern (Header + Payload)#
char header[] = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\n";
char body[] = "HELLO";
struct iovec iov[2];
iov[0].iov_base = header;
iov[0].iov_len = sizeof(header) - 1;
iov[1].iov_base = body;
iov[1].iov_len = sizeof(body) - 1;
// Atomic transmission without memcpy buffer concatenation
ssize_t total_written = writev(sock_fd, iov, 2);
if (total_written == -1) {
perror("writev");
}