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::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<u8> = 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<u8> = 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
}