From 9019b533a8c9a543b6b604bc96c9613e9baeb18f Mon Sep 17 00:00:00 2001 From: g1n Date: Fri, 23 Jul 2021 08:08:53 +0000 Subject: [PATCH] Add not builtin command - tail --- .gitignore | 1 + src/tail.rs | 42 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+) create mode 100644 src/tail.rs diff --git a/.gitignore b/.gitignore index 96ef6c0..73d5daf 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ /target +/bin Cargo.lock diff --git a/src/tail.rs b/src/tail.rs new file mode 100644 index 0000000..5df53f3 --- /dev/null +++ b/src/tail.rs @@ -0,0 +1,42 @@ +use std::env; +use std::fs::File; +use std::path::Path; +use std::io::BufReader; +use std::io::prelude::*; + +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: tail [OPTIONS] FILE"); + println!("Output the last part of files"); + }, + "-n" => { + num_of_lines = args[arg+1].parse::().unwrap(); + } + arg => { + if Path::new(arg).exists() { + get_line_at(Path::new(arg), num_of_lines); + } + } + } + } + Ok(()) +} + +fn get_line_at(path: &Path, line_num: i32) -> Result<(),()> { + let file = File::open(path).expect("File not found or cannot be opened"); + let content = BufReader::new(&file); + let lines = content.lines(); + let mut lines_vec: Vec = Vec::new(); + for line in lines { + lines_vec.push(line.unwrap()); + } + let line_num = lines_vec.len() - (line_num as usize); + for line in line_num..lines_vec.len() { + println!("{}", lines_vec[line]); + } + Ok(()) +}