grsh/src/head.rs

40 lines
1.3 KiB
Rust

use std::convert::TryInto;
use std::env;
use std::fs::File;
use std::io::prelude::*;
use std::io::stdout;
use std::io::BufReader;
use std::path::Path;
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(())
}