Skip to content

Instantly share code, notes, and snippets.

@mre
Created November 6, 2017 22:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mre/0669610090bd73d3c81fa3e4e49cf62c to your computer and use it in GitHub Desktop.
Save mre/0669610090bd73d3c81fa3e4e49cf62c to your computer and use it in GitHub Desktop.
A `cat` implemenation written in Rust using output buffering and stdio locking
#[macro_use]
extern crate error_chain;
use std::env;
use std::fs::File;
use std::io::{self, BufReader, Read, Write};
pub const BUFFER_CAPACITY: usize = 64 * 1024;
error_chain! {
foreign_links {
Io(std::io::Error);
}
}
fn run() -> Result<()> {
let stdout = io::stdout();
let mut locked = stdout.lock();
let mut buffer = [0u8; BUFFER_CAPACITY];
if let Some(path) = env::args().nth(1) {
let input = File::open(path)?;
let mut buffered = BufReader::new(input);
loop {
let bytes_read = buffered.read(&mut buffer);
if bytes_read.unwrap() == 0 {
break;
}
locked.write_all(&buffer)?;
}
}
Ok(())
}
quick_main!(run);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment