From dd0a754631ac4c7517683c76b7dd7eb436956c21 Mon Sep 17 00:00:00 2001 From: Hatter Jiang Date: Sat, 2 May 2020 11:54:13 +0800 Subject: [PATCH] add get_read_stdin_or_file --- src/util_io.rs | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/src/util_io.rs b/src/util_io.rs index 9cc55d0..6a9b93a 100644 --- a/src/util_io.rs +++ b/src/util_io.rs @@ -1,5 +1,6 @@ use std::{ + fs::File, io::{self, ErrorKind, prelude::*, @@ -7,13 +8,24 @@ use std::{ time::{SystemTime, Duration}, }; -use super::XResult; +use super::{ XResult, new_box_ioerror, }; use super::util_size::get_display_size; use super::util_msg::print_lastline; pub const DEFAULT_BUF_SIZE: usize = 8 * 1024; +pub fn get_read_stdin_or_file(file: &str) -> XResult> { + if file.is_empty() { + Ok(Box::new(io::stdin())) + } else { + match File::open(file) { + Ok(f) => Ok(Box::new(f)), + Err(err) => Err(new_box_ioerror(&format!("Open file {}, erorr: {}", file, err))), + } + } +} + pub fn read_to_string(read: &mut dyn Read) -> XResult { let mut buffer = String::new(); read.read_to_string(&mut buffer)?;