43 lines
1.2 KiB
Rust
43 lines
1.2 KiB
Rust
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(())
|
|
}
|