From 2bfeb4b22168e8cc996f27c75be3557f71c3c951 Mon Sep 17 00:00:00 2001 From: emma Date: Thu, 12 Jan 2023 23:54:12 -0500 Subject: [PATCH] cat(1): working implementation --- src/cat.rs | 77 +++++++++++++++++++++++++++--------------------------- 1 file changed, 38 insertions(+), 39 deletions(-) diff --git a/src/cat.rs b/src/cat.rs index 6e81ccd..9b968ea 100644 --- a/src/cat.rs +++ b/src/cat.rs @@ -18,9 +18,10 @@ */ use std::env; -use std::fs::{File, read_to_string}; +use std::fs::{ File, read_to_string }; +use std::os::fd::{ AsRawFd, FromRawFd }; use std::io; -use std::io::{ BufRead, Read }; +use std::io::{ BufRead, Read, Write }; use std::str; use arg::Args; @@ -46,57 +47,55 @@ fn main() -> ExitCode { ).unwrap(); let argv0 = args.argv0; - let mut output = String::new(); + let stdin = io::stdin(); if args.paths.is_empty() { args.paths.push("-".to_string()); } - - while args.u { - for path in &args.paths { + + if args.u { + for path in args.paths { + let handle: File; if path == "-" { - loop { - let mut buf = String::new(); - match io::stdin().lock().read_line(&mut buf) { - Ok(bytes) => { - if bytes == 0 { break }; - print!("{}", buf); - }, - Err(err) => println!("{}", err), - }; + handle = unsafe { + File::from_raw_fd(stdin.as_raw_fd()) } } else { - let mut input = String::new(); - match File::open(path) { - Ok(input) => {}, + handle = match File::open(&path) { + Ok(file) => file, Err(_) => { - println!("{}: {}: No such file or directory.", &argv0, path); + eprintln!("{}: {}: No such file or directory.", &argv0, &path); return ExitCode::NoInput; }, }; } - } - return ExitCode::Ok; - } + let mut stdout = io::BufWriter::with_capacity(0, io::stdout()); - for path in args.paths { - if path == "-" { - let mut bytes: Vec = Vec::new(); - io::stdin().lock().read_to_end(&mut bytes).unwrap(); - - for byte in &bytes { - output.push_str(str::from_utf8(&[byte.to_owned()]).unwrap()); + for byte in handle.bytes() { + stdout.write(&[byte.unwrap()]).unwrap(); + stdout.flush().unwrap(); } - } else { - match read_to_string(&path) { - Ok(contents) => { output.push_str(&contents) }, - Err(_) => { - eprintln!("{}: {}: No such file or directory.", &argv0, &path); - return ExitCode::NoInput; - }, - }; + } return ExitCode::Ok; + } else { + for path in args.paths { + if path == "-" { + let mut bytes: Vec = Vec::new(); + stdin.lock().read_to_end(&mut bytes).unwrap(); + + for byte in &bytes { + output.push_str(str::from_utf8(&[byte.to_owned()]).unwrap()); + } + } else { + match read_to_string(&path) { + Ok(contents) => { output.push_str(&contents) }, + Err(_) => { + eprintln!("{}: {}: No such file or directory.", &argv0, &path); + return ExitCode::NoInput; + }, + }; + } + print!("{}", output); + output.clear(); } - print!("{}", output); - output.clear(); } ExitCode::Ok }