Add not builtin command - head

This commit is contained in:
g1n 2021-07-22 17:16:26 +00:00
parent 9c75ad6ef9
commit e8de03ee0e
1 changed files with 39 additions and 0 deletions

39
src/head.rs Normal file
View File

@ -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<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: head [OPTIONS] FILE");
println!("Output the first part of files");
},
"-n" => {
num_of_lines = args[arg+1].parse::<i32>().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(())
}