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

> A practical guide to configuring OS file descriptors with `File::options()`, avoiding TOCTOU bugs, and designing zero-allocation APIs with `impl AsRef<Path>`.

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:

```bash
# 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 `HANDLE`s 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`:

```powershell
# 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](https://eagle2000.space/en/rust/rust-builder/)):

```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`):

| 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:

```rust
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>`:

**Before — Rigid API (**`&PathBuf`**):**

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

**After — Ergonomic API (**`impl AsRef<Path>`**, 0 extra allocations):**

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

- **Signature:** Instead of locking callers to a heap buffer (`path: &PathBuf`), accept any type that cheaply converts to `&Path` (`path: impl AsRef<Path>`).
- **String literal call:** A string literal `&str` implements `AsRef<Path>` directly, avoiding a heap allocation (`"config.toml"` instead of `&PathBuf::from("config.toml")`).

### 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.

---

## 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.

---

*Originally published on* [*EagleBlog*](https://eagle2000.space/en/rust/rust-files-tempfile-and-docs/)*, where you can also run the interactive Rust Playground slides and take the quiz.*
