File & Pipe
use std::fs; use std::process; use std::io::{self, Read}; use base64::{decode,encode}; fn write() { let src = "/etc/passwd"; let content = match fs::read_to_string(&src) { Ok(content) => content, Err(x) => { eprintln!("{}", x); process::exit(1); } }; let mut lines = content .split('\n') .filter(|x| !x.is_empty()) .collect::<Vec<&str>>(); lines.sort_unstable(); println!("{encoded}", encoded=encode(lines.join("\n"))); } fn read() { let dst = "/tmp/passwd"; let mut buffer = String::new(); io::stdin().read_to_string(&mut buffer).expect("We want some input."); let buffer = buffer.trim(); let decoded : String = match decode(&buffer) { Ok(res) => { String::from_utf8(res).expect("Valid utf8 string") }, Err(err) => { eprintln!("Invalid buffer: {:?}", err); process::exit(1); } }; match fs::write(&dst, decoded) { Ok(_res) => { println!("Wrote file {dst}.", dst=dst); }, Err(x) => { eprintln!("{}", x); } } } fn main() { if atty::is(atty::Stream::Stdin) { write(); } else { read(); } }
Run by doing:
$ cargo r|cargo r && wc -l /tmp/passwd
Wrote file /tmp/passwd.
53 /tmp/passwd