Skip to main content
Be Bitwise
CAssembly Equivalents of C Patterns

File I/O at the Syscall Level

In C you reach for fopen, fread, fwrite, fclose. Buffered I/O from the standard library. Underneath sit four raw syscalls: open, read, write, close. We'll implement file operations directly through syscalls in assembly, then put them next to the C library to see what the buffering layer is actually doing for you.

The Core File Syscalls

Linux provides four fundamental file syscalls (the numbers below are for x86-64; other architectures number them differently):

SyscallNumberArgumentsReturns
open2rdi=path, rsi=flags, rdx=modeFile descriptor in rax
read0rdi=fd, rsi=buffer, rdx=countBytes read in rax
write1rdi=fd, rsi=buffer, rdx=countBytes written in rax
close3rdi=fd0 on success in rax

A file descriptor is just an integer. Every process starts life with three of them:

  • 0 = stdin
  • 1 = stdout
  • 2 = stderr

open hands back the next available integer (typically 3, then 4, and so on).

Opening and Reading a File

A complete program that reads a file and dumps it to stdout:

asm
section .data
filename: db "test.txt", 0 ; Null-terminated filename
section .bss
buffer: resb 4096 ; 4KB read buffer
fd: resq 1 ; Space for file descriptor
section .text
global _start
_start:
; open("test.txt", O_RDONLY)
mov rax, 2 ; syscall: open
lea rdi, [rel filename] ; path
xor rsi, rsi ; flags: O_RDONLY = 0
xor rdx, rdx ; mode: 0 (ignored for O_RDONLY)
syscall
; Check for error (negative return = error)
test rax, rax
js .open_error
mov [rel fd], rax ; Save file descriptor
.read_loop:
; read(fd, buffer, 4096)
mov rax, 0 ; syscall: read
mov rdi, [rel fd] ; fd
lea rsi, [rel buffer] ; buffer
mov rdx, 4096 ; count
syscall
; Check return value
test rax, rax
jz .eof ; 0 = end of file
js .read_error ; negative = error
; write(stdout, buffer, bytes_read)
mov rdx, rax ; count = bytes actually read
mov rax, 1 ; syscall: write
mov rdi, 1 ; fd: stdout
lea rsi, [rel buffer] ; buffer
syscall
jmp .read_loop ; Continue reading
.eof:
; close(fd)
mov rax, 3 ; syscall: close
mov rdi, [rel fd] ; fd
syscall
; exit(0)
mov rax, 60
xor rdi, rdi
syscall
.open_error:
; Write error message and exit with code 1
mov rax, 1
mov rdi, 2 ; fd: stderr
lea rsi, [rel open_err_msg]
mov rdx, open_err_len
syscall
mov rax, 60
mov rdi, 1
syscall
.read_error:
mov rax, 3 ; Close the file first
mov rdi, [rel fd]
syscall
mov rax, 60
mov rdi, 1
syscall
section .data
open_err_msg: db "Error: could not open file", 10
open_err_len equ $ - open_err_msg

The Equivalent C Code

Compare to the C standard library version:

c
#include <stdio.h>
int main() {
FILE *f = fopen("test.txt", "r");
if (!f) {
perror("Error");
return 1;
}
char buffer[4096];
size_t n;
while ((n = fread(buffer, 1, 4096, f)) > 0) {
fwrite(buffer, 1, n, stdout);
}
fclose(f);
return 0;
}

The C version looks simpler, but fopen is doing extra work behind your back:

  • Allocates a FILE struct on the heap
  • Sets up an internal buffer (on glibc, the file's st_blksize capped at BUFSIZ, 8192, which works out at 4096 bytes for most regular files)
  • Stashes the file descriptor, buffer pointers, and mode flags

Follow each call down a layer and every f-function ends at one of the four syscalls from the table, with libc's FILE sitting between your code and the kernel:

Writing to a File

Creating and writing to a file means combining O_WRONLY, O_CREAT, and (usually) O_TRUNC:

asm
section .data
outfile: db "output.txt", 0
message: db "Hello from assembly!", 10
msg_len equ $ - message
; Flag values from Linux x86-64 headers (other OSes and some
; architectures use different numbers):
O_WRONLY equ 1
O_CREAT equ 64
O_TRUNC equ 512
section .text
write_to_file:
; open("output.txt", O_WRONLY | O_CREAT | O_TRUNC, 0644)
mov rax, 2 ; syscall: open
lea rdi, [rel outfile] ; path
mov rsi, O_WRONLY | O_CREAT | O_TRUNC ; flags = 577
mov rdx, 0o644 ; mode: rw-r--r-- (octal)
syscall
test rax, rax
js .error
mov rbx, rax ; Save fd
; write(fd, message, msg_len)
mov rax, 1 ; syscall: write
mov rdi, rbx ; fd
lea rsi, [rel message] ; buffer
mov rdx, msg_len ; count
syscall
; close(fd)
mov rax, 3
mov rdi, rbx
syscall
ret
.error:
ret

The 0o644 permission mode means:

  • Owner: read + write (6)
  • Group: read only (4)
  • Others: read only (4)

This is the same as chmod 644.

What C's Buffered I/O Actually Does

Call fwrite(data, 1, 100, fp) and the C library does NOT immediately invoke the write syscall. Instead:

  1. Your data gets copied into an internal buffer (glibc sizes it from the file's st_blksize, up to BUFSIZ = 8192; that's usually 4096 bytes for a regular file, and a terminal gets line buffering instead)
  2. Once the buffer fills, it flushes — one write call with a buffer's worth of bytes
  3. fclose shoves any leftover bytes through

Conceptually, the buffering looks like this:

c
// Simplified version of how stdio buffering works internally:
struct _FILE {
int fd;
char buf[8192];
int buf_pos;
int buf_size;
};
size_t my_fwrite(const void *data, size_t size, size_t count, struct _FILE *f) {
size_t total = size * count;
const char *src = data;
while (total > 0) {
size_t space = f->buf_size - f->buf_pos;
size_t to_copy = total < space ? total : space;
memcpy(f->buf + f->buf_pos, src, to_copy);
f->buf_pos += to_copy;
src += to_copy;
total -= to_copy;
if (f->buf_pos == f->buf_size) {
write(f->fd, f->buf, f->buf_size); // Flush!
f->buf_pos = 0;
}
}
return count;
}

The assembly equivalent is mechanical but tedious — pointer arithmetic and comparisons all the way down. The whole point is to slash syscall counts. Every syscall flips from user mode to kernel mode and back, which costs hundreds to thousands of cycles. Batching writes amortises that overhead away.

Measuring the Difference

Say you write a million single characters to a file:

c
// Unbuffered (raw syscalls): 1,000,000 write() syscalls
for (int i = 0; i < 1000000; i++) {
write(fd, "X", 1);
}
// Buffered (stdio, 4096-byte buffer): ~245 write() syscalls
// (244 full buffers, plus one partial flush at fclose)
for (int i = 0; i < 1000000; i++) {
fputc('X', fp);
}

About 245 syscalls instead of a million (check yours with strace -c). The speedup is enormous, often 100x or more. This is the chief reason the C standard library exists at all: it handles the buffering so you don't have to.

Seeking Within a File

The lseek syscall repositions the file offset:

asm
; lseek(fd, 100, SEEK_SET) - seek to byte 100 from start
mov rax, 8 ; syscall: lseek
mov rdi, rbx ; fd
mov rsi, 100 ; offset
mov rdx, 0 ; SEEK_SET = 0
syscall
; rax now contains the new file position

SEEK constants:

  • SEEK_SET (0) - from the beginning of the file
  • SEEK_CUR (1) - from the current position
  • SEEK_END (2) - from the end of the file

Error Handling at the Syscall Level

Linux syscalls signal errors with negative return values. Negate the return and you have the error code:

asm
mov rax, 2 ; open
lea rdi, [rel filename]
xor rsi, rsi
xor rdx, rdx
syscall
test rax, rax
js .error ; Negative = error
; rax is a valid file descriptor
jmp .success
.error:
neg rax ; Now rax = errno value
; Common values:
; 2 = ENOENT (no such file)
; 13 = EACCES (permission denied)
; 24 = EMFILE (too many open files)

The C library wraps this into the errno machinery: check for a negative return, stash the negated value in the thread-local errno, return -1 from the wrapper. You then peek at errno or call perror. Assembly hands you the error code straight up, no detour.

Key Takeaways

  1. File I/O boils down to four syscalls. open, read, write, close. Everything else (fopen, fread, fprintf, fseek) is layers on top.

  2. Buffering is the chief value the C library brings. Raw syscalls are simple and expensive; the library amortises the cost by batching.

  3. File descriptors are just integers. No "file object" exists at the OS level. The fd is an index into a per-process table the kernel maintains.

  4. Error handling is a sign convention. Negative return means error, magnitude is the error code. The C library dresses it up as errno for your convenience.