File I/O in Rust
From the Rust cheat sheet ยท Macros & File I/O ยท verified Jul 2026
File I/O
Read and write files with std::fs.
rust
use std::fs;
// Read entire file to string
let contents = fs::read_to_string("data.txt")?;
// Write string to file (creates or overwrites)
fs::write("output.txt", "Hello, world!")?;๐ก fs::read_to_string() and fs::write() are the quickest way to read/write files
โก Use BufReader for line-by-line reading โ much more memory efficient than read_to_string
๐ All fs operations return Result โ use ? to propagate errors
๐ข Use PathBuf::from("dir").join("file") for cross-platform path construction
filesiofspath