From c34accce65458baf6e03cbd77adbe7d3c18a55d8 Mon Sep 17 00:00:00 2001 From: g1n Date: Sat, 31 Jul 2021 16:00:59 +0000 Subject: [PATCH] wc: add lines count --- src/wc.rs | 24 +++++++++++++++--------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/src/wc.rs b/src/wc.rs index f58f356..ff3714d 100644 --- a/src/wc.rs +++ b/src/wc.rs @@ -2,29 +2,35 @@ use std::env; use std::fs::File; use std::path::Path; use std::io::BufReader; -use std::io::stdout; use std::io::prelude::*; fn main() -> std::io::Result<()> { let args: Vec = env::args().collect(); let mut only_chars = false; - let mut only_words = false; + let mut only_lines = false; Ok(for arg in 1..args.len() { match args[arg].as_str() { "-c" => { only_chars=true } - "-w" => { only_words=true } - "--help" => { - println!("Usage: cat [OPTIONS] FILE"); - println!("Reads a file"); - }, - arg => { + "-l" => { only_lines=true } + "--help" => { + println!("Usage: cat [OPTIONS] FILE"); + println!("Reads a file"); + }, + 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)?; + let mut lines = 0; + for _ in contents.lines() { + lines += 1; + } if only_chars { println!("{}", contents.len()); - stdout().flush().unwrap(); + } else if only_lines { + println!("{}", lines); + } else { + println!("{} {} {}", lines, contents.len(), arg); } } }