grsh/src/wc.rs

41 lines
1.3 KiB
Rust

use std::env;
use std::fs::File;
use std::io::prelude::*;
use std::io::BufReader;
use std::path::Path;
fn main() -> std::io::Result<()> {
let args: Vec<String> = env::args().collect();
let mut only_chars = false;
let mut only_lines = false;
Ok(for arg in 1..args.len() {
match args[arg].as_str() {
"-c" => only_chars = true,
"-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());
} else if only_lines {
println!("{}", lines);
} else {
println!("{} {} {}", lines, contents.len(), arg);
}
}
}
}
})
}