Skip to lesson content
navan✳THE BUILD LABRUST
0/53 complete
BUILD LAB / RUST/ PACKAGES, FILES & TOOLS
BUILD NOTE 32 / 53

Read the world outside main.

Propagate filesystem errors and avoid reading every file into memory.

BY NAVAN SAMI◷ 7 MIN READFOUNDATIONSRUST 2024

01 Understand the contract

Filesystem operations return Result because files may be missing, permissions may differ, and devices may fail. Path and PathBuf model platform paths without forcing them to be UTF-8 strings. read_to_string is convenient for small text files, while BufReader and BufRead::lines support streaming lines. Writing a path can truncate an existing file, so practice in a dedicated directory and make overwrite behavior part of the application contract. Return io::Result when the caller can handle filesystem failures.

02 Make it concrete

This is a complete standard-library example. Use Rust stable with the 2024 edition. Run it locally using the Rust workbench.

lessons/file-io/src/main.rs
use std::fs;
use std::io;
use std::path::Path;
fn main() -> io::Result<()> {
    let path = Path::new("lab-note.txt");
    fs::write(path, "build\ntest\n")?;
    let content = fs::read_to_string(path)?;
    println!("lines={}", content.lines().count());
    fs::remove_file(path)?;
    Ok(())
}
↳ EXPECTED OUTPUT
lines=2
  1. 1

    The example writes only its named practice file in the current directory.

  2. 2

    ? propagates I/O errors to main.

  3. 3

    The file is removed after reading.

From the extracted rust-workbench folder
cargo run -p lesson_file_io

03 Mind the boundary

04 Your next build

A SMALL MISSION

Read lines from an in-memory buffered cursor and collect nonempty lines.

Reveal one possible solution +
solutions/file-io/src/main.rs
use std::io::{BufRead, Cursor};
fn main() -> std::io::Result<()> {
    let lines: Vec<_> = Cursor::new("a\n\nb\n")
        .lines()
        .collect::<Result<Vec<_>, _>>()?
        .into_iter()
        .filter(|s| !s.is_empty())
        .collect();
    assert_eq!(lines, ["a", "b"]);
    Ok(())
}

05 Check your reasoning

QUICK SIGNAL CHECK

Which path type owns a path buffer?

ONE MORE CONTRACT YOU CAN EXPLAIN.

Understand it.
Then make it yours.

Run the example, try your own input, and explain the boundary. Log the lesson when the idea makes sense.

Built with curiosity. By Navan Sami. ↗Rust · Make the contract clear. Then build.