mlbright
mlbright

Reputation: 2202

How do I read and process N lines of a file at a time in Rust?

I would like to read N lines of a file at a time, possibly using itertools::Itertools::chunks.

When I do:

for line in stdin.lock().lines() {
   ... // this is processing one line at a time
}

... although I'm buffering input, I am not processing the buffer.

Upvotes: 3

Views: 2599

Answers (1)

Stargateur
Stargateur

Reputation: 26717

You could use chunks() from itertools:

use itertools::Itertools; // 0.8.0
use std::io::BufRead;

fn main() {
    let stdin = std::io::stdin();
    let n = 3;

    for lines in &stdin.lock().lines().chunks(n) {
        for (i, line) in lines.enumerate() {
            println!("Line {}: {:?}", i, line);
        }
    }
}

Upvotes: 5

Related Questions