-
Notifications
You must be signed in to change notification settings - Fork 0
/
tee.rs
72 lines (64 loc) · 1.78 KB
/
tee.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
use std::env;
use std::fs::OpenOptions;
use std::io;
use std::io::prelude::*;
fn main() -> io::Result<()> {
let args: Vec<String> = env::args().collect();
let mut append = false;
let mut ignore_interrupts = false;
let mut files = Vec::new();
// Parse arguments
let mut i = 1;
while i < args.len() {
let arg = &args[i];
match arg.as_ref() {
"-a" | "--append" => {
append = true;
i += 1;
}
"-i" | "--ignore-interrupts" => {
ignore_interrupts = true;
i += 1;
}
"--help" => {
print_help();
return Ok(());
}
"--version" => {
print_version();
return Ok(());
}
_ => {
files.push(arg);
i += 1;
}
}
}
// Read from standard input and write to standard output and files
let mut stdin = io::stdin();
let mut stdout = io::stdout();
let mut buffer = [0; 1024];
loop {
let bytes_read = stdin.read(&mut buffer)?;
if bytes_read == 0 {
break;
}
stdout.write_all(&buffer[..bytes_read])?;
for file in &files {
let mut file = OpenOptions::new()
.write(true)
.create(true)
.append(append)
.open(file)?;
file.write_all(&buffer[..bytes_read])?;
}
}
Ok(())
}
fn print_help() {
println!("Usage: tee [-ai] [--append] [--ignore-interrupts] [ file... ]");
println!(" tee [--help] [--version]");
}
fn print_version() {
println!("tee 0.1.0");
}