Add not builtin command - tail

This commit is contained in:
g1n 2021-07-23 08:08:53 +00:00
parent e8de03ee0e
commit 9019b533a8
2 changed files with 43 additions and 0 deletions

1
.gitignore vendored
View File

@ -1,2 +1,3 @@
/target
/bin
Cargo.lock

42
src/tail.rs Normal file
View File

@ -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<String> = 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::<i32>().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<String> = 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(())
}