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:
- Configuring OS file descriptors with the Builder pattern in
File::options()and how those methods map to POSIX flags. - The
PathvsPathBufpair, unsized types (DST), and designing ergonomic public APIs withimpl 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.logWindows: inspecting open HANDLEs
Windows does not expose /proc, so you can inspect open HANDLEs in two ways:
- Built-in Resource Monitor: run
resmon.exefrom PowerShell orWin + R, open the CPU tab, and check Associated Handles to see every file handle held by a process. - 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.
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.
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 withFile::open("app.log")and try towriteln!to it, Unix/Linux fails withBad file descriptor (os error 9)(on Windows,os error 5, Access Denied) because that descriptor lacks write permissions. - Calling
.create(true)without.appendor.truncate(os error 22):File::options().create(true).open("app.log")compiles fine, but returnsInvalidInput(“Invalid argument”) at runtime. The OS needs to know whether to append (.append(true)) or truncate (.truncate(true)/false). Runningcargo clippycatches this immediately with file opened withcreate, buttruncatebehavior not defined. - Simple one-liners: when you do not need custom flags or a long-lived handle,
std::fs::read_to_string(path)andstd::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):
| Concept | Borrowed Unsized Slice | Owned Heap Buffer |
|---|---|---|
| Text Data | &str | String |
| OS Native Strings | &OsStr | OsString |
| Filesystem Paths | &Path | PathBuf |
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>:
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"));
}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"));
}Three Practical Tips for impl AsRef<Path> and Path#
- Watch out for moves: because
path: impl AsRef<Path>is passed by value, callingfs::exists(path)movespath, so a subsequentfs::read_to_string(path)will not compile. Pass&pathinstead, or bindlet path = path.as_ref();at the top of the function. - Storing in structs and printing: to store the path inside a struct, convert it into an owned
PathBufwithPathBuf::from(path.as_ref())(or.to_path_buf()). When printing a&Path, call.display()becausePathdoes not implementDisplay(OS paths are not guaranteed to be valid UTF-8). - Prefer
std::fs::exists(Rust 1.81+):path.exists()silently returnsfalseon permission errors, whereasstd::fs::exists(&path)?returnsio::Result<bool>and surfaces real I/O failures.
Walk through the interactive slides below to see File::options() and impl AsRef<Path> in action:
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>:


