Archived
2
0

cat(1): works (real)

This commit is contained in:
Emma Tebibyte 2022-12-12 16:49:51 -05:00
parent edae70d313
commit ad45829309

View File

@ -35,53 +35,63 @@ struct Arguments {
paths: Vec<String>,
}
fn main() -> ExitCode {
let mut arguments = env::args().collect::<Vec<String>>();
let argv0 = arguments.remove(0);
let args = Arguments::from_args(arguments
.iter()
.map(String::as_str)
.collect::<Vec<&str>>()
).unwrap();
let mut val = String::new();
let mut output = String::new();
if args.paths.is_empty() {
match io::stdin().lock().read_line(&mut output) {
Ok(_) => { val.push_str(&output); },
Err(_) => {
eprintln!("Usage: {} [options...] [files...]", argv0);
return ExitCode::Usage;
},
};
} else {
for path in args.paths {
match read_to_string(&path) {
Ok(output) => { val.push_str(&output); },
Err(_) => {
eprintln!("{}: {}: No such file or directory.", argv0, &path);
return ExitCode::NoInput;
},
};
}
}
if args.u {
fn out(argv0: &str, u: bool, val: &str) -> ExitCode {
if u {
let mut stdout = unsafe { File::from_raw_fd(1) };
match stdout.write_all(&val.as_bytes()) {
match stdout.write_all(val.as_bytes()) {
Ok(_) => {},
Err(_) => {
eprintln!("{}: Cannot write to stdout", argv0);
return ExitCode::OsErr;
},
};
} else { print!("{}", &val); }
} else { print!("{}", val); }
ExitCode::Ok
}
fn main() -> ExitCode {
let mut arguments = env::args().collect::<Vec<String>>();
let argv0 = arguments.remove(0);
let mut args = Arguments::from_args(arguments
.iter()
.map(String::as_str)
.collect::<Vec<&str>>()
).unwrap();
let mut output = String::new();
if args.paths.is_empty() { args.paths.push("-".to_string()); }
for path in args.paths {
if path == "-" {
loop {
match io::stdin().lock().read_line(&mut output) {
Ok(EOF) => {
out(&argv0, args.u, &output);
output.clear();
if EOF == 0 { break }
},
Err(_) => {
eprintln!("Usage: {} [options...] [files...]", &argv0);
return ExitCode::Usage;
},
};
}
} else {
match read_to_string(&path) {
Ok(output) => { out(&argv0, args.u, &output); },
Err(_) => {
eprintln!("{}: {}: No such file or directory.", &argv0, &path);
return ExitCode::NoInput;
},
};
}
}
match io::stdout().flush() {
Ok(_) => return ExitCode::Ok,
Err(_) => {
eprintln!("{}: Cannot write to stdout", argv0);
eprintln!("{}: Cannot write to stdout", &argv0);
return ExitCode::OsErr;
},
};