From 5b47345bf5fba339c277ec5808adccbc6d4d511f Mon Sep 17 00:00:00 2001 From: emma Date: Mon, 5 Dec 2022 20:59:40 -0500 Subject: [PATCH] added stdin support to cat --- src/rs/cat.rs | 37 ++++++++++++++++++++++++++++--------- 1 file changed, 28 insertions(+), 9 deletions(-) diff --git a/src/rs/cat.rs b/src/rs/cat.rs index 4929bfd..14106f5 100644 --- a/src/rs/cat.rs +++ b/src/rs/cat.rs @@ -2,7 +2,8 @@ // SPDX-License-Identifier: AGPL-3.0-or-later use std::fs::read_to_string; -use std::io::{stdin, stdout, Write}; +use std::io; +use std::io::Write; use std::env; use std::process; @@ -25,7 +26,7 @@ fn main() { "-u" => {}, _ => { - println! ("Usage: {} [options...] [files...]", argv0); + println!("Usage: {} [options...] [files...]", argv0); process::exit(64); // sysexits(3) EX_USAGE }, }; @@ -33,15 +34,33 @@ fn main() { } else { for path in args { - match read_to_string(&path) { - Ok(val) => println!("{}", val), - Err(_) => { - println!("{}: {}: No such file or directory.", argv0, path); - process::exit(66); // sysexits(3) EX_NOINPUT + let mut val = String::new(); + + match path.as_str() { + "-" => { + let mut content = String::new(); + match io::stdin().read_line(&mut content) { + Ok(_) => { val.push_str(&content); }, + Err(_) => { + println!("Usage: {} [options...] [files...]", argv0); + process::exit(64); // sysexits(3) EX_USAGE + }, + }; }, - }; + + _ => { + match read_to_string(&path) { + Ok(output) => { val.push_str(&output); }, + Err(_) => { + println!("{}: {}: No such file or directory.", argv0, path); + process::exit(66); // sysexits(3) EX_NOINPUT + }, + }; + }, + } + print!("{}", val); } } - stdout().flush().unwrap(); + io::stdout().flush().unwrap(); }