On this page
  1. CLI File Processor with Result & ?
  2. Streaming Line Filter (Zero External Crates)

CLI File Processor with Result & ?

Prev: tutorials | Up: tutorials | Next: Concurrent Worker Pool with Channels
Rel: BufReader, Result
Ref: Rust std — std::io
Tags: #public #prog #rust #tutorials #io


Streaming Line Filter (Zero External Crates)

use std::env;
use std::error::Error;
use std::fs::File;
use std::io::{BufRead, BufReader};

fn count_matching_lines(path: &str, needle: &str) -> Result<usize, Box<dyn Error>> {
    let reader = BufReader::new(File::open(path)?);
    let mut matches = 0;
    for line in reader.lines() {
        if line?.contains(needle) {
            matches += 1;
        }
    }
    Ok(matches)
}

fn main() -> Result<(), Box<dyn Error>> {
    let mut args = env::args().skip(1);
    let path = args.next().ok_or("usage: grepcount <file> <needle>")?;
    let needle = args.next().ok_or("missing needle")?;
    println!("matches = {}", count_matching_lines(&path, &needle)?);
    Ok(())
}

Linked from

Related notes