Rust Tutorial: File I/O
Read and write files with std::fs, handle errors with Result, and work with paths.
Working with files
Rust's standard library provides straightforward file I/O. All operations return `Result` — forcing you to handle errors explicitly.
What you'll learn in this Rust file i/o tutorial
This interactive Rust tutorial has 8 hands-on exercises. Estimated time: 18 minutes.
- Read a file — `fs::read_to_string` reads an entire file into a String.
- Write a file — `fs::write` creates or overwrites a file.
- Handle file errors — Use match or ? to handle file not found and other errors.
- Append to a file — `OpenOptions` lets you open files with specific modes.
- Read line by line — `BufReader` reads efficiently line by line without loading the whole file.
- Paths — `Path` and `PathBuf` handle file paths in a cross-platform way.
- fs::read for binary — `fs::read` returns `Vec<u8>` — useful for binary files.
- Walk a directory — `fs::read_dir` lists directory contents.
Rust File I/O concepts covered
- Working with files