Rust read a text file line by line with BufReader
Rust
use std::fs::File;
use std::io::{self, BufRead, BufReader};
use std::path::Path;
fn read_lines(path: impl AsRef<Path>) -> io::Result<Vec<String>> {
let file = File::open(path)?;
let reader = BufReader::new(file);
let mut lines = Vec::new();
for line in reader.lines() {
lines.push(line?);
}
Ok(lines)
}
fn main() -> io::Result<()> {
for (n, line) in read_lines("notes.txt")?.iter().enumerate() {
println!("{}: {}", n + 1, line);
}
Ok(())
}