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
- tuts/rust/tutorials Linked here; links to this page; shared tags: #prog, #rust, #tutorials
- tuts/rust/tutorials/concurrent_worker_pool_channels Linked here; links to this page; shared tags: #prog, #rust, #tutorials
- tuts/rust/builtins/Result Linked here; shared tags: #prog, #rust
- tuts/rust/std/io_and_fs/BufReader Linked here; shared tags: #prog, #rust
- tuts/interop/rust_and_python_pyo3_maturin shared tags: #prog, #rust, #tutorials
- tuts/rust/tutorials/zero_copy_parsing_with_lifetimes shared tags: #prog, #rust, #tutorials
- tuts/c/stdlib/stdio_and_file_io shared tags: #io, #prog
- tuts/c/tutorials shared tags: #prog, #tutorials
- tuts/c/tutorials/arena_allocator_pattern shared tags: #prog, #tutorials
- tuts/c/tutorials/c_shared_library_with_python_ctypes shared tags: #prog, #tutorials