use anyhow::{Context, Result}; use clap::Parser; use indicatif::ProgressBar; use std::fs::File; use std::io::{self, BufRead, Write}; use std::path::PathBuf; use std::thread; use std::time::Duration; /// 在文件中搜索模式并显示包含它的行。 #[derive(Parser)] struct Cli { /// 要查找的模式 pattern: String, /// 要读取的文件的路径 path: PathBuf, } fn main() -> Result<()> { let args = Cli::parse(); // 打开文件并创建一个 BufReader 来逐行读取 let file = File::open(&args.path).with_context(|| format!("无法打开文件 {:?}", &args.path))?; let reader = io::BufReader::new(file); let stdout = io::stdout(); let stdout_lock = stdout.lock(); let mut handle = io::BufWriter::new(stdout_lock); let pb = ProgressBar::new(100); for line in reader.lines() { do_hard_work(); pb.println(format!("[+] 查找到了 #{:?}项", line)); pb.inc(1); let line = line.with_context(|| "无法读取行")?; if line.contains(&args.pattern) { writeln!(handle, "{}", line)?; } } Ok(()) } fn do_hard_work() { thread::sleep(Duration::from_millis(250)); }