Archived
2
0

cat(1): working implementation

This commit is contained in:
Emma Tebibyte 2023-01-12 23:54:12 -05:00
parent c33d9e0556
commit 2bfeb4b221

View File

@ -18,9 +18,10 @@
*/ */
use std::env; 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;
use std::io::{ BufRead, Read }; use std::io::{ BufRead, Read, Write };
use std::str; use std::str;
use arg::Args; use arg::Args;
@ -46,57 +47,55 @@ fn main() -> ExitCode {
).unwrap(); ).unwrap();
let argv0 = args.argv0; let argv0 = args.argv0;
let mut output = String::new(); let mut output = String::new();
let stdin = io::stdin();
if args.paths.is_empty() { args.paths.push("-".to_string()); } if args.paths.is_empty() { args.paths.push("-".to_string()); }
while args.u { if args.u {
for path in &args.paths { for path in args.paths {
let handle: File;
if path == "-" { if path == "-" {
loop { handle = unsafe {
let mut buf = String::new(); File::from_raw_fd(stdin.as_raw_fd())
match io::stdin().lock().read_line(&mut buf) {
Ok(bytes) => {
if bytes == 0 { break };
print!("{}", buf);
},
Err(err) => println!("{}", err),
};
} }
} else { } else {
let mut input = String::new(); handle = match File::open(&path) {
match File::open(path) { Ok(file) => file,
Ok(input) => {},
Err(_) => { Err(_) => {
println!("{}: {}: No such file or directory.", &argv0, path); eprintln!("{}: {}: No such file or directory.", &argv0, &path);
return ExitCode::NoInput; return ExitCode::NoInput;
}, },
}; };
} }
} let mut stdout = io::BufWriter::with_capacity(0, io::stdout());
return ExitCode::Ok;
}
for path in args.paths { for byte in handle.bytes() {
if path == "-" { stdout.write(&[byte.unwrap()]).unwrap();
let mut bytes: Vec<u8> = Vec::new(); stdout.flush().unwrap();
io::stdin().lock().read_to_end(&mut bytes).unwrap();
for byte in &bytes {
output.push_str(str::from_utf8(&[byte.to_owned()]).unwrap());
} }
} else { } return ExitCode::Ok;
match read_to_string(&path) { } else {
Ok(contents) => { output.push_str(&contents) }, for path in args.paths {
Err(_) => { if path == "-" {
eprintln!("{}: {}: No such file or directory.", &argv0, &path); let mut bytes: Vec<u8> = Vec::new();
return ExitCode::NoInput; 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 ExitCode::Ok
} }