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

> A practical guide to files and paths in Rust: configuring POSIX flags with File::options(), Path vs PathBuf, and designing ergonomic APIs with impl AsRef<Path>.

- **URL:** https://eagle2000.space/en/rust/rust-files-tempfile-and-docs/
- **Date:** 2026-12-03

- **Tags:** rust, dev, files, builder-pattern, path, pathbuf

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

{{< spoiler title="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
```
{{< /spoiler >}}

{{< spoiler title="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
   ```
{{< /spoiler >}}

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

{{< alert "comment" >}}
**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.
{{< /alert >}}

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](../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.

{{< alert "comment" >}}
**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).
{{< /alert >}}

### 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>`**:

{{< code-before-after before_label="Rigid API (&PathBuf)" after_label="Ergonomic API (impl AsRef<Path>)" badge="0 extra allocs" caption="Comparison: impl AsRef<Path> accepts &str, String, &Path, and PathBuf with zero extra allocations at the call site" >}}
```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"));
}
```
===
```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 ;; path: &PathBuf ;; path: impl AsRef<Path> ;; Instead of locking callers to a heap buffer, accept any type that cheaply converts to &Path.
String literal call ;; &PathBuf::from("config.toml") ;; "config.toml" ;; A string literal &str implements AsRef<Path> directly, avoiding a heap allocation.
{{< /code-before-after >}}

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

```rust
// Step 1: Configuring file descriptors via File::options()

use std::fs::File;
use std::io::Write;
use anyhow::Result;

pub fn append_telemetry_log(file_path: &str, entry: &str) -> Result<()> {
    // Calling File::options() is an application of the Builder pattern for file flags:
    let mut log_file = File::options()
        .create(true) // Create the file if it does not exist yet
        .append(true) // Append bytes strictly to the end without overwriting
        .open(file_path)?;

    writeln!(log_file, "[LOG]: {entry}")?;
    Ok(())
}

fn main() {
    let result = append_telemetry_log("system_events.log", "Auth service started successfully");
    match result {
        Ok(()) => println!("Entry successfully appended to the log file"),
        Err(err) => println!("File access error: {err}"),
    }
}
```

**1. The Builder pattern in File::options()**
- I covered the Builder pattern in detail in [The Builder Pattern in Rust](../rust-builder/).
- The standard library uses this pattern in `File::options()` to clearly configure OS file-opening modes (`read`, `write`, `append`, `create_new`).


#### Step 2

```rust
// Step 2: Flexible path types with impl AsRef<Path> and Path vs PathBuf

use std::fs;
use std::path::{Path, PathBuf};

// Using `impl AsRef<Path>` lets the function accept &str, String, Path, and PathBuf without explicit cloning:
pub fn inspect_file_size(path: impl AsRef<Path>) -> std::io::Result<u64> {
    let path_ref: &Path = path.as_ref(); // Borrow an immutable path slice (unsized Path)
    let metadata = fs::metadata(path_ref)?;
    Ok(metadata.len())
}

fn main() {
    // PathBuf is an owned, mutable path on the heap (analogous to String).
    let mut owned_path = PathBuf::from(".");
    owned_path.push("config.json");
    let _ = fs::write(&owned_path, r#"{"env": "prod"}"#);

    // &str is a standard string slice.
    let str_path = "system_events.log";
    let _ = fs::write(str_path, "service started\n");

    // Both variables of different types work with the same function via impl AsRef<Path>:
    match inspect_file_size(&owned_path) {
        Ok(size) => println!("Size of {:?} (PathBuf): {size} bytes", owned_path),
        Err(err) => println!("Read error {:?}: {err}", owned_path),
    }
    match inspect_file_size(str_path) {
        Ok(size) => println!("Size of {:?} (&str): {size} bytes", str_path),
        Err(err) => println!("Read error {:?}: {err}", str_path),
    }
}
```

**2. Path, PathBuf, and the `impl AsRef<Path>` trait**
- `Path` is a borrowed dynamically sized path slice (DST, analogous to `&str`).
- `PathBuf` is an owned, mutable path on the heap (analogous to `String`).
- `impl AsRef<Path>` lets your API accept `&str`, `String`, `&Path`, and `PathBuf` without extra conversions.


---

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


### 📝 File Modes, Path, and PathBuf


**1. What is the main advantage of `File::options()` when opening files?**

- [ ] It automatically compresses files with gzip
- [ ] It applies the Builder pattern, offering clear, chainable methods to configure file descriptor flags (`.create(true).append(true)`)
- [ ] It replaces OS system calls with an in-memory emulator

**2. What is the difference between `Path` and `PathBuf`?**

- [ ] `Path` is only for files, while `PathBuf` is only for directories
- [ ] `Path` is only available in test builds
- [ ] `Path` is an unsized, borrowed path slice (like `&str`), while `PathBuf` is an owned, heap-allocated path (like `String`)

**3. Why should function parameters accept `impl AsRef<Path>`?**

- [ ] It lets callers pass `&str`, `String`, `&Path`, or `PathBuf` without manual conversions
- [ ] It speeds up reading files from NVMe SSDs
- [ ] It prevents permission-denied errors at compile time

**4. Which `File::options()` method atomically creates a new file and fails with `AlreadyExists` if it already exists?**

- [ ] `.truncate(true)`
- [ ] `.append(true)`
- [ ] `.create_new(true)` (maps to `O_CREAT | O_EXCL` on POSIX)

**5. What does `.append(true)` (`O_APPEND` on POSIX) do when opening a file?**

- [ ] Overwrites the file from the beginning, erasing existing data
- [ ] Opens the file in read-only mode
- [ ] Appends all writes strictly to the end of the file without erasing existing content

**6. What happens when you open an existing non-empty file with `.truncate(true)` (`O_TRUNC`)?**

- [ ] Its size is reset to 0 bytes upon opening
- [ ] The file is copied into the system temp directory
- [ ] Writes are appended to the end of the file

**7. Why can't you declare a bare `let p: Path;` variable directly on the stack in Rust?**

- [ ] `Path` requires administrator privileges to allocate
- [ ] `Path` is a DST (Dynamically Sized Type), so the compiler does not know how many bytes to reserve on the stack
- [ ] `Path` can only exist inside `async` functions

**8. What does `&Path` store under the hood?**

- [ ] Only a 64-bit memory address
- [ ] Only the byte length of the path
- [ ] A fat pointer containing both the memory address and the byte length

**9. What is the TOCTOU (Time-of-Check to Time-of-Use) bug in `if !path.exists() { File::create(path)?; }`?**

- [ ] Between `exists()` and `File::create()`, another process can create the file and your code will overwrite it
- [ ] `exists()` always returns `false` on Windows
- [ ] `File::create()` cannot create files in the working directory

**10. What does `path.push("app.log")` do on a `PathBuf`?**

- [ ] Creates an empty `app.log` file on disk
- [ ] Appends a path segment using the current OS separator (`/` or `\`)
- [ ] Removes the last path component

**11. Does calling `path.set_extension("json")` on a `PathBuf` rename the actual file on disk?**

- [ ] Yes, it immediately renames the file on the filesystem
- [ ] No, it only updates the in-memory path inside `PathBuf`
- [ ] Yes, if the file was opened with `.write(true)`

**12. Why are `Path` and `PathBuf` built on `OsStr` / `OsString` instead of `str` / `String`?**

- [ ] Because OS file paths are not guaranteed to be valid UTF-8
- [ ] Because `String` cannot contain slash characters in Rust
- [ ] Because `OsStr` always fits in 8 bytes

**13. How do `File::open(path)` and `File::create(path)` differ from `File::options()`?**

- [ ] `File::open` and `File::create` use fixed flag presets, whereas `File::options()` lets you combine flags freely
- [ ] `File::open` only works on Linux while `File::options()` only works on Windows
- [ ] `File::options()` does not return `std::io::Result`

**14. What does each configuration method on `File::options()` (such as `.read(true)` or `.create(true)`) return before `.open()` is called?**

- [ ] A ready-to-use `File` handle
- [ ] `&mut Self` so you can chain more options
- [ ] A boolean `true` or `false`

**15. What is a file descriptor (`fd`) on Unix/POSIX systems?**

- [ ] An integer index into the process's open-resource table used by the OS to identify an open file, socket, or pipe
- [ ] A filename together with its extension
- [ ] A hidden metadata file stored next to the binary

**16. How does `std::fs::File` prevent file descriptor leaks in Rust?**

- [ ] By periodically restarting the process
- [ ] Through RAII and `Drop`: when `File` leaves scope, the OS descriptor is closed automatically
- [ ] By capping every file at 1 KB

**17. Which three standard file descriptors are open by default when a process starts?**

- [ ] `0` for `stdin`, `1` for `stdout`, `2` for `stderr`
- [ ] `1` for `config`, `2` for `temp`, `3` for `log`
- [ ] None; a process must open every stream manually

