Compare commits

...
3 Commits
Author SHA1 Message Date
Ian Rettig 4f1f96c108 Feat: add in stdio read
following the tutorial for this.
2025-06-11 11:36:03 -04:00
Ian Rettig 0f24dd22a7 Feat: Add word counter binary. 2025-06-11 11:25:34 -04:00
Ian Rettig 28d6c8cccd Move main to grrs in bin directory. 2025-06-11 11:20:34 -04:00
2 changed files with 42 additions and 0 deletions
+42
View File
@@ -0,0 +1,42 @@
use clap::{CommandFactory, Parser};
use std::{
fs::File,
io::{stdin, BufRead, BufReader, IsTerminal},
path::PathBuf,
};
/// Count the number of lines in a file
#[derive(Parser)]
#[command(arg_required_else_help = true)]
struct Cli {
/// The path to the file to read, use - to read from stdin (must not be a tty)
file: PathBuf,
}
fn main() {
let args = Cli::parse();
let word_count;
let mut file = args.file;
if file == PathBuf::from("-") {
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_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
}
View File