Files & Data · 16 min · free lesson

Save & Read a Text File

Make the file effect explicit, return errors, and verify the bytes that came back.

Core idea

A successful write is not a promise of crash-safe durability.

Diagram for Save & Read a Text File: a Rust code example flows to the lesson rule and the key observation.
Fallible filesystem effects in a granted directory

Understand it

A small report can keep parsing pure and put file access in a narrow adapter. Accept a borrowed Path, write UTF-8 text, read it back, and return io::Result<String>. The question mark propagates the real I/O error to the caller. An unreadable destination, missing parent directory, or invalid UTF-8 on a later read is not equivalent to an empty report.

Local compiler profile: standard library with Crabrix's writable /sandbox directory. That is a guest path granted by the runtime, not arbitrary access to the iPhone's Files library. The verification harness chooses a sandbox path on wasm32 and a temporary working-directory path for the desktop test. It checks empty text, multiline text, Unicode, and replacement of an existing file. The lesson does not request network or account access.

fs::write creates or truncates the target. That is appropriate for this exercise's replace-the-report contract, but it can destroy an older report before a new write finishes. A crash-safe save strategy typically writes a sibling temporary file, flushes and syncs as required, then replaces the destination. Atomic rename and durability details depend on the host filesystem; do not advertise a portable power-loss guarantee from a single write call.

Round-trip equality proves the observed contents for this run. It does not prove every possible failure mode or make concurrent writers safe. If two participants edit a shared Playground, coordinate document updates before asking either participant to save a local copy. A remote output event must never silently trigger the filesystem effect on another device. Keep execution and saving explicit actions owned by the local user.

Read the code

use std::{fs, io};
fn main() -> io::Result<()> {
    // Crabrix guest path; choose a local path for desktop Cargo.
    fs::write("/sandbox/report.txt", "crab: 3\n")?;
    let text =
        fs::read_to_string("/sandbox/report.txt")?;
    assert_eq!(text, "crab: 3\n");
    Ok(())
}

Fallible filesystem effects in a granted directory

Try it

Use fs::write and fs::read_to_string, propagating errors. Return the exact saved text; do not append to an existing file. In the Crabrix app, open the compiler lab and complete the supplied function in solution.rs. The reading question is a separate exercise.

What success looks like: The local compiler accepts the changed solution and the separate verification harness finishes all normal and boundary cases. Printing a success message alone does not complete this lab.

Check your understanding

What does fs::write do to an existing target?

Reveal the answer
  1. It appends automatically
  2. It creates or truncates the file
  3. It guarantees a power-loss-safe transaction

The target is created or truncated. Crash-safe replacement and durability are separate design requirements.

Go deeper

Common misconception: Writing a file automatically makes the save transactional.

Creation/truncation, atomic replacement, and durable persistence are distinct guarantees.

  1. Choose authority: Use only a destination granted by the local runtime.
  2. Perform effect: Propagate write and read errors with question marks.
  3. Verify: Compare exact text, including empty input and Unicode.

Transfer challenge: Design a temporary-file replacement sequence for desktop Cargo and list what could fail at each step.

Connections

  • Paths & Boundaries: Path, PathBuf, and lexical validation
  • Validate Data Records: A bounded text format with precise errors