Read a file line by line in Rust using File, BufReader, and the lines() iterator.
Use std::fs::File with BufReader and the lines() iterator to read a file line by line.
use std::fs::File;
use std::io::{self, BufRead, BufReader};
fn main() -> io::Result<()> {
let file = File::open("hello.txt")?;
let reader = BufReader::new(file);
for line in reader.lines() {
let line = line?;
println!("{line}");
}
Ok(())
}
Reading a file line by line in Rust opens the file and processes it one line at a time instead of loading the whole thing into memory at once. This approach is useful for handling large text files efficiently without crashing your computer. Think of it like reading a book page by page rather than trying to memorize the entire story before starting.