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
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);
}
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.