Skip to content

Instantly share code, notes, and snippets.

@stevedoyle
Last active December 28, 2023 22:29
Show Gist options
  • Save stevedoyle/8e7e8916f79b582cc12b8a0bb9d995c9 to your computer and use it in GitHub Desktop.
Save stevedoyle/8e7e8916f79b582cc12b8a0bb9d995c9 to your computer and use it in GitHub Desktop.
Read text file line by line using Rust.
// From: https://doc.rust-lang.org/rust-by-example/std_misc/file/read_lines.html
use std::fs::File;
use std::io::{self, BufRead};
use std::path::Path;
fn main() {
// File hosts.txt must exist in the current path
if let Ok(lines) = read_lines("./hosts.txt") {
// Consumes the iterator, returns an (Optional) String
for line in lines.flatten() {
println!("{}", line);
}
}
}
// The output is wrapped in a Result to allow matching on errors.
// Returns an Iterator to the Reader of the lines of the file.
fn read_lines<P>(filename: P) -> io::Result<io::Lines<io::BufReader<File>>>
where
P: AsRef<Path>,
{
let file = File::open(filename)?;
Ok(io::BufReader::new(file).lines())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment