use std::{env, fs, process}; struct Config { file_path: String, command: String } impl Config { fn new(args: &[String]) -> Result { if args.len() < 3 || args.len() == 0 { return Err("invalid arguments") } let path = args[2].clone(); let command = args[1].clone(); Ok(Config { file_path: path, command }) } } fn main() { let args: Vec = env::args().collect(); let config = Config::new(&args).unwrap_or_else(|_err| { print_help(); process::exit(1) }); let file_contents = fs::read_to_string(config.file_path).expect("Invalid file path, please make sure the path to the file is correct"); match config.command.as_str() { "-c" | "--bytes" => count_bytes(&file_contents), "-l" | "--lines" => count_lines(&file_contents), "-w" | "--words" => count_words(&file_contents), "-m" | "--chars" => count_chars(&file_contents), "-h" | "--help" => print_help(), _ => print_help(), } } fn count_bytes(contents: &String) { println!("{}", contents.bytes().len()) } fn count_chars(contents: &String) { println!("{}", contents.chars().count()) } fn count_lines(contents: &String) { println!("{}", contents.lines().count()) } fn count_words(contents: &String) { print!("{}", contents.split_whitespace().count()) } fn print_help() { println!(" yap [-COMMAND] [PATH_TO_FILE] -c, --bytes - count the amount of bytes in a file -l, --lines - count the amount of lines in a file -w, --words - count the amount of words in a file -m, --chars - count the amount of characters in a file -h, --help - list the available command line arguments " ); }