Rust:
Reading a text file

How to:

Rust’s standard library makes it straightforward to read files.

use std::fs::File;
use std::io::{self, Read};

fn main() -> io::Result<()> {
    let mut file = File::open("example.txt")?;
    let mut contents = String::new();
    file.read_to_string(&mut contents)?;
    println!("File Contents:\n{}", contents);
    Ok(())
}

This code opens “example.txt”, reads it, and prints the contents.

Sample output:

File Contents:
Hello, Rustaceans!

Deep Dive

Historically, file IO can be complex, but Rust simplifies it. There are alternatives to read_to_string, like using BufRead for line-by-line handling, which is more efficient on larger files. Under the hood, Rust’s file reading leverages OS-level system calls, buffering data for efficiency.

Post-Rust 1.0, the language emphasizes safe system interactions – reading a file is no exception. The Result type encapsulates potential errors, making Rust robust against common pitfalls like missing files or permission issues without resorting to panics.

See Also

Additional resources to check out: