Skip to content

Instantly share code, notes, and snippets.

@eblocha
Last active May 1, 2023 03:02
Show Gist options
  • Save eblocha/8ad70f5a8bd7173011baccd43416279e to your computer and use it in GitHub Desktop.
Save eblocha/8ad70f5a8bd7173011baccd43416279e to your computer and use it in GitHub Desktop.
Rust function to generify a file or stdin for command line apps. If a path is provided, it will return a readable file handle, or stdin if no path is provided.
use std::{fs, io, path::Path};
fn file_or_stdin<P>(path: Option<P>) -> io::Result<Box<dyn io::Read + 'static>>
where
P: AsRef<Path>,
{
match path {
None => Ok(Box::new(io::BufReader::new(io::stdin()))),
Some(path) => match fs::File::open(path) {
Ok(file) => Ok(Box::new(io::BufReader::new(file))),
Err(err) => {
return Err(err);
}
},
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment