How To Read a File Line-by-Line in Rust

Created
Modified

Using lines Method

The method lines() returns an iterator over the lines of a file. The following example:

use std::fs::File;
use std::io::{self, BufRead};
use std::path::Path;

fn main() {
  if let Ok(lines) = read_lines("file.txt") {
    for line in lines {
      if let Ok(text) = line {
        println!("{}", text)
      }
    }
  }
}

// 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>,
{
  // open a file in read-only mode
  let file = File::open(filename)?;
  Ok(io::BufReader::new(file).lines())
}
First line.
Second line.

Related Tags

#read# #file# #line#