Read a string line by line in Rust using the lines() iterator on a BufReader.
Use the lines() iterator on a File to process each line sequentially.
use std::fs::File;
use std::io::{self, BufRead};
fn main() -> io::Result<()> {
let file = File::open("input.txt")?;
let reader = io::BufReader::new(file);
for line in reader.lines() {
let line = line?;
println!("{line}");
}
Ok(())
}
Reading a string line by line in Rust processes a file one line at a time instead of loading the whole thing into memory. It is like reading a book page by page rather than trying to hold the entire book in your hands at once. You use this when processing large text files to keep your program fast and efficient.