Feat: add in stdio read

following the tutorial for this.
This commit is contained in:
Ian Rettig
2025-06-11 11:36:03 -04:00
parent 0f24dd22a7
commit 4f1f96c108
+28 -8
View File
@@ -1,22 +1,42 @@
use clap::Parser; use clap::{CommandFactory, Parser};
use std::path::PathBuf; use std::{
fs::File,
io::{stdin, BufRead, BufReader, IsTerminal},
path::PathBuf,
};
/// Count the number of lines in a file /// Count the number of lines in a file
#[derive(Parser)] #[derive(Parser)]
#[command(arg_required_else_help = true)] #[command(arg_required_else_help = true)]
struct Cli { struct Cli {
/// The path to the file to read /// The path to the file to read, use - to read from stdin (must not be a tty)
file: PathBuf, file: PathBuf,
} }
fn main() { fn main() {
let args = Cli::parse(); let args = Cli::parse();
let mut word_count = 0; let word_count;
let file = args.file; let mut file = args.file;
for line in std::fs::read_to_string(&file).unwrap().lines() { if file == PathBuf::from("-") {
word_count += line.split(' ').count(); if stdin().is_terminal() {
Cli::command().print_help().unwrap();
::std::process::exit(2);
}
file = PathBuf::from("<stdin>");
word_count = words_in_buf_reader(BufReader::new(stdin().lock()));
} else {
word_count = words_in_buf_reader(BufReader::new(File::open(&file).unwrap()));
} }
println!("Words in {}: {}", file.to_str().unwrap(), word_count) println!("Words in {}: {}", file.to_string_lossy(), word_count)
}
fn words_in_buf_reader<R: BufRead>(buf_reader: R) -> usize {
let mut count = 0;
for line in buf_reader.lines() {
count += line.unwrap().split(' ').count()
}
count
} }