From e8de03ee0e50f500d158560360793e6031859d0a Mon Sep 17 00:00:00 2001 From: g1n Date: Thu, 22 Jul 2021 17:16:26 +0000 Subject: [PATCH] Add not builtin command - head --- src/head.rs | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 src/head.rs diff --git a/src/head.rs b/src/head.rs new file mode 100644 index 0000000..097c96c --- /dev/null +++ b/src/head.rs @@ -0,0 +1,39 @@ +use std::env; +use std::fs::File; +use std::path::Path; +use std::io::BufReader; +use std::io::stdout; +use std::io::prelude::*; +use std::convert::TryInto; + +fn main() -> std::io::Result<()> { + let args: Vec = env::args().collect(); + let mut num_of_lines: i32 = 10; + for arg in 1..args.len() { + match args[arg].as_str() { + "--help" => { + println!("Usage: head [OPTIONS] FILE"); + println!("Output the first part of files"); + }, + "-n" => { + num_of_lines = args[arg+1].parse::().unwrap(); + } + arg => { + if Path::new(arg).exists() { + let file = File::open(arg)?; + let mut buf_reader = BufReader::new(file); + let mut contents = String::new(); + buf_reader.read_to_string(&mut contents)?; + for (index, line) in contents.lines().enumerate() { + print!("{}\n", line); + if index + 1 >= num_of_lines.try_into().unwrap() { + break; + } + } + stdout().flush().unwrap(); + } + } + } + } + Ok(()) +}