wc: add lines count

This commit is contained in:
g1n 2021-07-31 16:00:59 +00:00
parent 11fe516693
commit c34accce65
1 changed files with 15 additions and 9 deletions

View File

@ -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<String> = 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);
}
}
}