Created
November 6, 2017 22:57
-
-
Save mre/0669610090bd73d3c81fa3e4e49cf62c to your computer and use it in GitHub Desktop.
A `cat` implemenation written in Rust using output buffering and stdio locking
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#[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