Streaming file search
Quick answer
Streaming search reads a file incrementally rather than loading it entirely into memory. A buffered reader amortizes I/O overhead.
Separate the reader from the file
Accept impl BufRead so the same function can read a file, stdin or a Cursor in a test. lines decodes UTF-8 and strips line endings, and may return an I/O or decoding error. Propagate errors instead of quietly dropping them. A line-based implementation still allocates an entire line; untrusted input requires a line-size cap or incremental byte scanner. This example handles small trusted local text.
use std::io::{self, BufRead, Cursor};fn count(r: impl BufRead, needle: &str) -> io::Result<usize> { let mut total = 0; for line in r.lines() { if line?.contains(needle) { total += 1; } } Ok(total)}fn main() { println!("{}", count(Cursor::new(b"red\nblue\nred fox\n"), "red").unwrap()); }Expected stdout (not executed):
2This counts matching lines, not occurrences.
use std::io::{BufRead, Cursor};fn main() { let mut lines = Cursor::new([0xff_u8, b'\n']).lines(); println!("{}", lines.next().unwrap().is_err());}Expected stdout (not executed):
trueA binary input is not automatically a valid text file.
Common mistake
Do not use filter_map(Result::ok) if missing unreadable lines would change the result.
Try it yourself
Change the search to report matching line numbers starting at one.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Streaming file search — practice quiz
Choose one answer per question. Code examples are predictions; review explanations after attempting them.
A streaming search reads line by line from an untrusted file. What extra resource check is important?
Streaming file search — example 1. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust use std::io::{self, BufRead, Cursor}; fn count(r: impl BufRead, needle: &str) -> io::Result<usize> { let mut total = 0; for line in r.lines() { if line?.contains(needle) { total += 1; } } Ok(total) } fn main() { println!("{}", count(Cursor::new(b"red\nblue\nred fox\n"), "red").unwrap()); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.
Streaming file search — example 2. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust use std::io::{BufRead, Cursor}; fn main() { let mut lines = Cursor::new([0xff_u8, b'\n']).lines(); println!("{}", lines.next().unwrap().is_err()); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.