BufReader Repeat first line

Using std::io::BufReader::read_line(&mut String) to process a file a line at a time and the first line is read twice.

use std::fs::File;
use std::io::BufRead;
use std::io::BufReader;
fn main() -> std::io::Result<()>{
    let file_name = "/tmp/saved";
    let file = File::open(file_name)?;
    let mut buf_reader = BufReader::new(file);
    let mut line:String = String::new();
    while buf_reader.read_line(&mut line)? != 0 {
        print!("{}", line);
    }
    Ok(())
}

/tmp/saved has as content:

first
second

The output is:

first
first
second

It is actually read once, but printed twice.

From https://doc.rust-lang.org/std/io/trait.BufRead.html#method.read_line, emphasis mine:

Read all bytes until a newline (the 0xA byte) is reached, and append them to the provided buffer.

So after the second line is read your line is the whole contents of the file.

2 Likes

Very helpful, thank you.
std::io::Lines was what I should have used

use std::fs::File;
use std::io::BufRead;
use std::io::BufReader;
fn main() -> std::io::Result<()>{
    let file_name = "/tmp/saved";
    let file = File::open(file_name)?;
    let  buf_reader = BufReader::new(file);
    let  lines = buf_reader.lines();
    for line in lines  {
        println!("{}", line.unwrap());
    }
    Ok(())
}

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.