From 5befe69b3f4ae57d4dbd366268acedb48b63678f Mon Sep 17 00:00:00 2001 From: 53hornet Date: Thu, 5 Aug 2021 11:41:41 -0400 Subject: read from stdin if filename is missing --- src/main.rs | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/src/main.rs b/src/main.rs index da0e599..fb030d0 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,20 +1,20 @@ +use std::io::BufReader; use std::{env, fs::File, io::Read}; fn main() -> Result<(), Box> { const CHUNK_SIZE: usize = 8; + let mut file: Box; - let filename = env::args().nth(1).unwrap_or_default(); - if filename.is_empty() { - eprintln!("error missing filename"); - return Ok(()); - } + file = if let Some(filename) = env::args().nth(1) { + Box::new(BufReader::new(File::open(&filename)?)) + } else { + Box::new(BufReader::new(std::io::stdin())) + }; - let mut file = File::open(&filename)?; let mut chunk = Vec::with_capacity(CHUNK_SIZE); let mut idx = 0; while { - chunk.clear(); file.by_ref() .take(CHUNK_SIZE as u64) .read_to_end(&mut chunk)? @@ -31,6 +31,7 @@ fn main() -> Result<(), Box> { // write ascii println!("{}", String::from_utf8_lossy(&chunk).replace('\n', "⏎")); idx += CHUNK_SIZE; + chunk.clear(); } Ok(()) -- cgit v1.2.3