↓ Skip to main content
  1. Rust/

File Modes, Builder Pattern, and Path / PathBuf in Rust

1803 words·9 mins· loading · loading · · ·Rust-middle

Introduction
#

Almost every CLI tool, web service, or database eventually hits disk I/O. In Rust, the filesystem API is designed to avoid redundant allocations and prevent accidental descriptor bugs.

In this guide, I’ll walk through two core topics for filesystem work:

  1. Configuring OS file descriptors with the Builder pattern in File::options() and how those methods map to POSIX flags.
  2. The Path vs PathBuf pair, unsized types (DST), and designing ergonomic public APIs with impl AsRef<Path>.

1. File Descriptors and the Builder Pattern in File::options()
#

What Is a File Descriptor?
#

When a program opens a file, network socket, or pipe, the operating system does not hand over raw disk access. Instead, it creates an entry in the process’s open-file table and returns a small integer (like 3 or 4) called a file descriptor (fd). Every process starts with three standard descriptors already open: 0 for stdin, 1 for stdout, and 2 for stderr.

On Windows, the equivalent kernel identifier is a HANDLE. Rust’s std::fs::File wraps this OS handle and automatically closes it when the File goes out of scope (via Drop), preventing descriptor leaks.

How to Inspect File Descriptors in the Terminal
#

Linux and macOS: listing open file descriptors

On Linux, a process’s open descriptors appear as symlinks inside /proc/<PID>/fd. You can bind a test file to descriptor 3 directly in your shell and inspect the table:

# 1. Attach test.log to file descriptor 3
exec 3> test.log

# 2. List open descriptors for the current shell ($$ is its PID)
ls -la /proc/$$/fd
# Linux output: 0 -> /dev/pts/0, 1 -> /dev/pts/0, 2 -> /dev/pts/0, 3 -> /tmp/test.log

# On macOS (no /proc), use lsof instead:
lsof -p $$

# 3. Close descriptor 3 and remove the test file
exec 3>&- && rm test.log
Windows: inspecting open HANDLEs

Windows does not expose /proc, so you can inspect open HANDLEs in two ways:

  1. Built-in Resource Monitor: run resmon.exe from PowerShell or Win + R, open the CPU tab, and check Associated Handles to see every file handle held by a process.
  2. In PowerShell / CMD using Microsoft Sysinternals handle.exe:
    # Show all open handles for notepad.exe
    handle.exe -p notepad.exe

Mapping to POSIX System Calls
#

At the OS level, Unix/POSIX and Windows require access bitmasks when opening a file via open(2) or CreateFileW.

What is POSIX? It is a family of standards for Unix-like operating systems (such as Linux, macOS, and FreeBSD) that defines common system calls and constants for files, processes, and sockets. Windows uses its own native API (CreateFileW), and Rust’s standard library automatically translates File::options() into the right OS-specific flags for each platform.

In POSIX, these flags are represented as constants:

  • O_RDONLY - open for reading only.
  • O_WRONLY | O_CREAT - open for writing, creating the file if it does not exist.
  • O_APPEND - append all writes strictly to the end of the file.
  • O_EXCL - fail if the file already exists (atomic creation guarantee).
  • O_TRUNC - truncate the file size to 0 upon opening.

Rust’s File::open(path) and File::create(path) provide common presets for these flags. Whenever you need a custom combination (for example, opening a file for both reading and appending without truncating), use std::fs::OpenOptions or File::options().

Quick cheat sheet:

  • Read-only: File::open(path)
  • Create or truncate to zero (O_TRUNC): File::create(path)
  • Create if missing and append: File::options().create(true).append(true).open(path)

Applying the Builder Pattern
#

File::options() returns a configuration builder using the Builder pattern (covered in detail in The Builder Pattern in Rust):

use std::fs::File;

let mut file = File::options()
    .read(true)        // Enables read mode
    .write(true)       // Combined with .read(true), maps to O_RDWR
    .create(true)      // Creates the file if missing (O_CREAT)
    .append(true)      // Moves the write cursor to the end (O_APPEND)
    .open("app.log")?;

Each method updates the builder’s internal state and returns &mut Self, while the final .open() call executes the OS syscall.

How do you create a file without overwriting an existing one? If you first check if !path.exists() and then call File::create(), another process can create a file with the same name in between those two steps, and your code will silently overwrite it (a TOCTOU race condition: Time-of-Check to Time-of-Use). Use .create_new(true) instead: the OS performs the existence check and file creation as a single atomic step, returning AlreadyExists if the file is already there (which maps to O_CREAT | O_EXCL on POSIX).

Common Pitfalls with Descriptors and File::options()
#

  • Writing to a read-only file (os error 9): if you open a file with File::open("app.log") and try to writeln! to it, Unix/Linux fails with Bad file descriptor (os error 9) (on Windows, os error 5, Access Denied) because that descriptor lacks write permissions.
  • Calling .create(true) without .append or .truncate (os error 22): File::options().create(true).open("app.log") compiles fine, but returns InvalidInput (“Invalid argument”) at runtime. The OS needs to know whether to append (.append(true)) or truncate (.truncate(true)/false). Running cargo clippy catches this immediately with file opened with create, but truncate behavior not defined.
  • Simple one-liners: when you do not need custom flags or a long-lived handle, std::fs::read_to_string(path) and std::fs::write(path, data) are much shorter.

2. Path Types Anatomy: Path vs PathBuf and impl AsRef<Path>
#

A Strict Analogy with String Types
#

Filesystem paths in Rust follow the exact same design as string types (&str and String):

ConceptBorrowed Unsized SliceOwned Heap Buffer
Text Data&strString
OS Native Strings&OsStrOsString
Filesystem Paths&PathPathBuf

Why Is Path an Unsized Type (DST)?
#

Most Rust types have a fixed size known at compile time (a u64 is always 8 bytes). DSTs (Dynamically Sized Types), such as str, [T], and Path (a thin wrapper around OsStr), do not: the byte length of a path like "/var/log/app.log" is only known at runtime.

Because the compiler cannot reserve an unknown number of bytes on the stack, you can never create a bare let p: Path; variable. Instead, Path always lives behind a reference or smart pointer like &Path or Box<Path>. Under the hood, &Path is a fat pointer that carries both the memory address and the byte length of the path.

In contrast, PathBuf owns a growable byte buffer on the heap and lets you mutate paths safely at runtime:

use std::path::PathBuf;

let mut path = PathBuf::from("/var/log");
path.push("eagleblog");       // Inserts the OS separator ('/' on Unix, '\' on Windows)
path.push("telemetry.log");
path.set_extension("json");   // Changes extension to /var/log/eagleblog/telemetry.json

Ergonomic APIs with impl AsRef<Path>
#

When designing a library or service module, taking concrete types like fn save_data(path: &PathBuf) or fn save_data(path: &str) is a common API mistake: callers either have to allocate a PathBuf::from(...) unnecessarily, or cannot pass an existing PathBuf directly.

The idiomatic solution is accepting impl AsRef<Path>:

Rigid API (&PathBuf)
use std::path::PathBuf;
use std::fs;

pub fn read_file_content(path: &PathBuf) -> std::io::Result<String> {
    fs::read_to_string(path)
}

fn main() {
    // Callers are forced to allocate a PathBuf:
    let _ = read_file_content(&PathBuf::from("config.toml"));
}
Hover or click a step to highlight matching lines:
Select or hover a step above to highlight matching lines in both columns.
Ergonomic API (impl AsRef<Path>)
use std::path::Path;
use std::fs;

pub fn read_file_content(path: impl AsRef<Path>) -> std::io::Result<String> {
    fs::read_to_string(path.as_ref())
}

fn main() {
    // Works with any path-like type without conversions:
    let _ = read_file_content("config.toml");
    let _ = read_file_content(&PathBuf::from("config.toml"));
}
Comparison: impl AsRef<Path> accepts &str, String, &Path, and PathBuf with zero extra allocations at the call site

Three Practical Tips for impl AsRef<Path> and Path
#

  1. Watch out for moves: because path: impl AsRef<Path> is passed by value, calling fs::exists(path) moves path, so a subsequent fs::read_to_string(path) will not compile. Pass &path instead, or bind let path = path.as_ref(); at the top of the function.
  2. Storing in structs and printing: to store the path inside a struct, convert it into an owned PathBuf with PathBuf::from(path.as_ref()) (or .to_path_buf()). When printing a &Path, call .display() because Path does not implement Display (OS paths are not guaranteed to be valid UTF-8).
  3. Prefer std::fs::exists (Rust 1.81+): path.exists() silently returns false on permission errors, whereas std::fs::exists(&path)? returns io::Result<bool> and surfaces real I/O failures.

Walk through the interactive slides below to see File::options() and impl AsRef<Path> in action:

Builder in File::options(), Path, PathBuf, and AsRef<Path>
Step 1/2
 1// Step 1: Configuring file descriptors via File::options()
 2
 3use std::fs::File;
 4use std::io::Write;
 5use anyhow::Result;
 6
 7pub fn append_telemetry_log(file_path: &str, entry: &str) -> Result<()> {
 8    // Calling File::options() is an application of the Builder pattern for file flags:
 9    let mut log_file = File::options()
10        .create(true) // Create the file if it does not exist yet
11        .append(true) // Append bytes strictly to the end without overwriting
12        .open(file_path)?;
13
14    writeln!(log_file, "[LOG]: {entry}")?;
15    Ok(())
16}
17
18fn main() {
19    let result = append_telemetry_log("system_events.log", "Auth service started successfully");
20    match result {
21        Ok(()) => println!("Entry successfully appended to the log file"),
22        Err(err) => println!("File access error: {err}"),
23    }
24}
25

1. The Builder pattern in File::options()

  • I covered the Builder pattern in detail in The Builder Pattern in Rust.
  • The standard library uses this pattern in File::options() to clearly configure OS file-opening modes (read, write, append, create_new).

Further Reading
#

Most of these patterns come from John Arundel’s book “The Secrets of Rust: Tools”. Chapter 5, “Files” (pages 89–114), walks through file descriptors, File::options(), Path, PathBuf, and AsRef<Path> using the logbook CLI project.


Test Your Knowledge!
#

Take a quick quiz on file modes, Path / PathBuf, and AsRef<Path>:

Article read
Please rate how helpful and clear this article was to you
▶ Article series
About Rust - This article is part of a series.

Related