I am currently reading Michael Kerrisk's book, The Linux Programming Interface. This is one of the exercises from the end of chapter 4 (I'm working in Rust, not C).
A Rust implementation of the tee
program on UNIX systems. According to it's man page
The tee utility copies standard input to standard output, making a copy in zero or more files. The output is unbuffered.
So running echo "foo" | tee
will print "foo" to the terminal.
running echo "foo" | tee myfile
will print "foo" to the terminal and also create the file myfile
with the contents "foo".
It's a small example but I'd love feedback on whether this is idiomatic Rust code and whether the efficiency could be improved.
use std::env;
use std::io::{self, Read};
use std::io::prelude::Write;
use std::error::Error;
use std::fs::File;
fn main() {
let fname = match env::args().nth(1) {
Some(name) => name,
None => String::from("/dev/null"),
};
let mut outfile = match File::create(&fname) {
Ok(file) => file,
Err(why) => panic!("{}", why.description()),
};
loop {
let mut line = String::new();
match io::stdin().read_to_string(&mut line) {
Ok(_) => {}
Err(_) => std::process::exit(0),
}
if line.is_empty() {
std::process::exit(0);
}
println!("{}", &line);
let _ = outfile.write(line.as_bytes());
}
}
tee
in Rust. \$\endgroup\$