Skip to content
systemcoding.dev
Systems Programming

Read and Write Files in Rust with std::fs and BufReader

Read and write files in Rust safely with std::fs and BufReader, understanding why unbuffered reads are slow and how Result propagation replaces manual checks.

7 min read
Summarize in AI
Flat illustration of a magnifier over lines of a log, with the Rust, C and C++ logos.

Reading and writing files is usually the first real systems operation a newcomer to Rust tries, and it immediately introduces two ideas central to the rest of the language: Result for fallible operations, and automatic resource cleanup through the Drop trait, the direct equivalent of C++'s RAII covered in the companion guide to modern C++ systems programming. This post covers both, plus the buffering distinction that separates a toy example from genuinely efficient file I/O, on Rust 1.84.

Opening and reading a whole file

std::fs::read_to_string is the simplest entry point, reading an entire file into a String in one call and returning a Result the caller must handle.

read_whole_file.rsrust
use std::fs;

fn main() {
    match fs::read_to_string("/etc/hostname") {
        Ok(content) => println!("contents: {}", content.trim()),
        Err(e) => eprintln!("failed to read: {}", e),
    }
}
Text
$ rustc -O read_whole_file.rs -o read_whole_file
$ ./read_whole_file
contents: myhost

There is no equivalent of forgetting to check the return value here the way a C program checking fopen's return against NULL could simply be skipped by a careless author: Result carries a #[must_use] attribute in the standard library, and the compiler emits a warning (promotable to an error with #[deny(unused_must_use)]) if a Result is produced and never examined, matched on, or propagated.

Opening a file explicitly and reading with a buffer

For anything beyond a single, simple read, opening the file explicitly and wrapping it in a BufReader is the idiomatic next step, and it matters for a concrete, measurable reason: reading a file line by line or in small chunks without a buffer issues one read() syscall per operation, while BufReader reads a larger block into memory once and serves subsequent small reads from that in-memory buffer, reducing the number of actual syscalls dramatically for line-oriented processing.

buffered_read.rsrust
use std::fs::File;
use std::io::{BufRead, BufReader};

fn main() -> std::io::Result<()> {
    let file = File::open("/etc/hosts")?;
    let reader = BufReader::new(file);

    let mut count = 0;
    for line in reader.lines() {
        let line = line?;
        if !line.starts_with('#') {
            count += 1;
        }
    }

    println!("{} non-comment lines", count);
    Ok(())
}
Text
$ rustc -O buffered_read.rs -o buffered_read
$ ./buffered_read
3 non-comment lines

reader.lines() returns an iterator of Result<String, io::Error>, since reading any individual line can still fail (invalid UTF-8, an I/O error partway through), and the ? inside the loop propagates that specific line's error immediately if one occurs, exactly the same propagation mechanism used at the function's own top level for the initial File::open call.

Writing a file, with and without buffering

Writing follows the identical pattern: std::fs::write for a single, simple write of a whole buffer, or an explicit File wrapped in a BufWriter for repeated, incremental writes where batching matters for performance.

buffered_write.rsrust
use std::fs::File;
use std::io::{BufWriter, Write};

fn main() -> std::io::Result<()> {
    let file = File::create("/tmp/output.txt")?;
    let mut writer = BufWriter::new(file);

    for i in 1..=5 {
        writeln!(writer, "line {}", i)?;
    }

    writer.flush()?;
    println!("wrote 5 lines");
    Ok(())
}
Text
$ rustc -O buffered_write.rs -o buffered_write
$ ./buffered_write
wrote 5 lines
$ cat /tmp/output.txt
line 1
line 2
line 3
line 4
line 5

The explicit writer.flush()? call before the function returns is worth calling out specifically: BufWriter's Drop implementation does flush any remaining buffered data when the writer goes out of scope, but that implicit flush inside Drop cannot report an error, since a destructor in Rust, like one in C++, has no good way to propagate a failure to its caller. Flushing explicitly, and checking the Result it returns with ?, is the only way to actually detect a write failure that happens to occur during the final flush, rather than silently losing that error the way relying on the implicit drop-time flush alone would.

Checking whether a file exists before opening it

A common beginner pattern, checking Path::exists() before calling File::open, carries a subtle race worth knowing about: the file's existence can change between the check and the subsequent open, another process deleting it in between, which means the check-then-open pattern is not actually race-free despite looking like it handles the "file missing" case correctly. The more robust pattern is to attempt the open directly and match specifically on the resulting error kind.

open_or_create.rsrust
use std::fs::File;
use std::io::ErrorKind;

fn main() {
    match File::open("/tmp/maybe_missing.txt") {
        Ok(_) => println!("file exists and opened successfully"),
        Err(e) if e.kind() == ErrorKind::NotFound => {
            println!("file does not exist; creating it instead");
            File::create("/tmp/maybe_missing.txt").unwrap();
        }
        Err(e) => eprintln!("unexpected error: {}", e),
    }
}
Text
$ rustc -O open_or_create.rs -o open_or_create
$ ./open_or_create
file does not exist; creating it instead

ErrorKind::NotFound is a portable, platform-independent variant the standard library maps the underlying OS error onto, analogous to checking std::errc::no_such_file_or_directory against a std::error_code in the companion C++ guide's own non-throwing-overloads post, rather than comparing a raw, platform-specific errno number directly.

Reading in fixed-size chunks for a large file

Neither read_to_string nor BufReader::lines() suits a genuinely large file where loading the whole thing into memory at once is undesirable; reading into a fixed-size buffer in a loop, checking how many bytes each call actually returned, is the Rust equivalent of the chunked reading pattern the companion C++ guide covers for std::ifstream.

chunked_read.rsrust
use std::fs::File;
use std::io::Read;

fn main() -> std::io::Result<()> {
    let mut file = File::open("/etc/hostname")?;
    let mut buf = [0u8; 16];
    let mut total = 0;

    loop {
        let n = file.read(&mut buf)?;
        if n == 0 {
            break; // end of file
        }
        total += n;
    }

    println!("read {} bytes in 16-byte chunks", total);
    Ok(())
}
Text
$ rustc -O chunked_read.rs -o chunked_read
$ ./chunked_read
read 9 bytes in 16-byte chunks

read() returning Ok(0) is the documented signal for end-of-file, distinct from an error, which mirrors the same end-of-stream convention the companion C++ guide's gcount()-based short-read detection relies on; a loop that does not check for the zero case specifically would spin forever once the file is exhausted, since a further read() call past end-of-file continues to succeed with zero bytes rather than returning an error.

Appending to an existing file

Both File::create and the simpler std::fs::write truncate an existing file to empty before writing, which is the right default for generating a fresh report but wrong for a log file or anything meant to grow across multiple runs; OpenOptions gives explicit, composable control over exactly which mode a file is opened in.

append_write.rsrust
use std::fs::OpenOptions;
use std::io::Write;

fn main() -> std::io::Result<()> {
    let mut file = OpenOptions::new()
        .create(true)
        .append(true)
        .open("/tmp/log.txt")?;

    writeln!(file, "a new log entry")?;
    println!("appended one line");
    Ok(())
}
Text
$ rustc -O append_write.rs -o append_write
$ ./append_write
appended one line
$ ./append_write
appended one line
$ cat /tmp/log.txt
a new log entry
a new log entry

.create(true) means the call succeeds whether or not the file already existed, creating it on the first run and reusing it on every subsequent one, while .append(true) guarantees every write lands at the current end of the file rather than at whatever position a separate seek call might have left the cursor at, which matters specifically for a log file multiple processes might write to concurrently, since O_APPEND-backed appends (the underlying POSIX flag this option maps to) are atomic with respect to the write's own positioning in a way a manual seek-then-write pair from a different process racing against it would not be.

Reaching for OpenOptions explicitly whenever a file's opening mode genuinely matters, rather than relying on File::create's truncating default out of habit, is a small discipline that prevents a surprising, silent data loss the first time that function is called against a file meant to accumulate rather than reset.

A short comment at the call site naming the chosen mode and why it was chosen pays for itself the first time someone else reads the code and wonders whether the truncation was deliberate.

It is a small habit with an outsized payoff relative to the few seconds it takes to write.

Share

Keep reading

Flat illustration of two options weighed side by side, with the macOS, Linux and Apple logos.
Kernels

Mach Traps vs BSD System Calls on macOS

Learn how macOS routes one trap instruction to either a Mach trap or a BSD system call, how the number sign and class decide, and why you should call libSystem.

8 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.