BufReader Reads File Lines Incrementally

Stream file lines with BufReader and lines(), propagate io errors with ?, and tally valid versus invalid records without loading the whole file.

RustData Integrity

Code

rustsnippet
31 lines
use std::fs::{self, File};
use std::io::{self, BufRead, BufReader};

fn tally_readings(path: &str) -> io::Result<(usize, usize)> {
    let reader = BufReader::new(File::open(path)?);
    let (mut valid, mut invalid) = (0, 0);

    for line in reader.lines() {
        let line = line?; // 读取失败(如设备断开)向上传播
        let trimmed = line.trim();
        if trimmed.is_empty() {
            continue;
        }
        match trimmed.parse::<f64>() {
            Ok(_) => valid += 1,
            Err(_) => invalid += 1,
        }
    }
    Ok((valid, invalid))
}

fn main() -> io::Result<()> {
    let path = "readings.txt";
    fs::write(path, "21.5\nbad\n18.2\n\n99.9\n")?;

    let (valid, invalid) = tally_readings(path)?;
    println!("valid {valid}, invalid {invalid}");

    fs::remove_file(path)?;
    Ok(())
}

What the code does

Count the functions tally_readings and main as the entire surface area of BufReader Reads File Lines Incrementally.

Iteration happens inside for line in reader.lines() — everything outside it runs once. The function returns Result, so handling the error arm is not optional. The match covers the value’s shapes one arm at a time — nothing falls to a default by accident.

What to watch for

  • The ? operators are load-bearing: delete one and the error handling becomes your job.

Applying it

The main signature takes this shape: fn tally_readings(path: &str) -> io::Result<(usize, usize)>

Labeled output is expected — valid — when the file runs.

The entry point wires tally_readings together — run it once and the whole demo flows.

Statements that matter

fs::write(path, "21.5\nbad\n18.2\n\n99.9\n")?;
let (valid, invalid) = tally_readings(path)?;
let line = line?; // 读取失败(如设备断开)向上传播
let trimmed = line.trim();

Interactive Tools for This Topic

FAQ

How do errors reach the caller?
Each fallible operation returns `Result`; nothing is silently discarded.
What does BufReader Reads File Lines Incrementally print when run?
Invoke the file as-is — the `valid` prefixes identify which step printed each line.