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

More Rust tasks

Back to the full Rust cheat sheet