Practical Rust
File I/O
Write, Read, Parse
Standard-library file functions write and read text. The example writes a number, reads it back, and parses it.
Program
Play the program to round-trip a number through a temporary file.
file_io.rs
Replay: real traced execution (multi-file project)
use std::fs;
fn main() {
let path = std::env::temp_dir().join(format!("egtry_rust_{}.txt", std::process::id()));
fs::write(&path, "42\n").unwrap();
let contents = fs::read_to_string(&path).unwrap();
let number: i32 = contents.trim().parse().unwrap();
fs::remove_file(&path).unwrap();
println!("{}", number * 2);
}
path ← "/tmp/⟨tmp A⟩.txt", contents ← "42\n", number ← 42
3fn main() {4 let pat→ "/tmp/⟨tmp A⟩.txt"h = std::env::temp_dir().join(format!("egtry_rust_{}.txt", std::process::id()));5 fs::write(&pat"/tmp/⟨tmp A⟩.txt"h, "42\n").unwrap();6 let content→ "42\n"s = fs::read_to_string(&pat"/tmp/⟨tmp A⟩.txt"h).unwrap();7 let numbe→ 42r: i32 = contents.trim().parse().unwrap();8 fs::remove_file(&pat"/tmp/⟨tmp A⟩.txt"h).unwrap();9 println!("{}", number * 2);10}output84
fs::write
`fs::write` saves text to a file path.
read_to_string
`fs::read_to_string` loads the file back as text.
parse
`trim().parse()` converts the text to a number.