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; -1 on error (errno set)
  • 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 when O_CREAT is specified

Access Modes (Specify exactly one)#

  • O_RDONLY: Open for read-only
  • O_WRONLY: Open for write-only
  • O_RDWR: Open for reading and writing

Common Creation and Status Flags#

  • O_CREAT: Create file if it does not exist
  • O_EXCL: Used with O_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 zero
  • O_APPEND: Atomically updates file offset to end of file before each write. Prevents race conditions between multiple processes appending to the same file (eliminates lseek(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 across exec calls 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 read
    • 0: End-of-File (EOF) reached
    • -1: Error occurred (errno set)
  • 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; -1 on error (errno set)
  • 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: 0 on success; -1 on error (errno set)
  • 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) -1 on error (errno set)
  • 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 file
  • SEEK_CUR: Offset is set relative to the current file position
  • SEEK_END: Offset is set relative to the end of the file (EOF)

Standard File Descriptors#

DescriptorMacroStream
0STDIN_FILENOStandard Input (stdin)
1STDOUT_FILENOStandard Output (stdout)
2STDERR_FILENOStandard 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 MethodTarget StructureOffset Sharing
dup() / dup2()Refers to the same Open File Description within the same processShared (reads/writes in one FD advance the offset for both)
fork()Child process inherits FD table pointing to the same Open File DescriptionShared (parent and child share file offsets)
Separate open() callsEach call allocates an independent Open File DescriptionIndependent (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 copies oldfd’s pointer into it.
  • dup2(oldfd, newfd): Atomically closes newfd (if already open) and copies oldfd’s pointer into newfd. Returns newfd.

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");
}