rwc
This commit is contained in:
parent
65fe3e800b
commit
163540889c
@ -1,4 +1,7 @@
|
||||
use std::env;
|
||||
use std::cmp::max;
|
||||
use std::fs::File;
|
||||
use std::io::Read;
|
||||
use std::process;
|
||||
|
||||
fn main() {
|
||||
@ -9,4 +12,47 @@ fn main() {
|
||||
}
|
||||
let filename = &args[1];
|
||||
// Your code here :)
|
||||
let mut file =
|
||||
File::open(filename).expect(format!("Cannot open file: {}\n", filename).as_str());
|
||||
let mut buffer = [0; 1024];
|
||||
let mut line_count = 0;
|
||||
let mut word_count = 0;
|
||||
let mut byte_count = 0;
|
||||
let mut skip_ws = false;
|
||||
let mut in_word = false;
|
||||
loop {
|
||||
let rd_size = file
|
||||
.read(&mut buffer)
|
||||
.expect(format!("Error reading file: {}", filename).as_str());
|
||||
if rd_size == 0 {
|
||||
break;
|
||||
}
|
||||
byte_count += rd_size;
|
||||
for v in buffer {
|
||||
if v == b'\n' {
|
||||
line_count += 1;
|
||||
}
|
||||
if v.is_ascii_whitespace() {
|
||||
if in_word && !skip_ws {
|
||||
skip_ws = true;
|
||||
in_word = false;
|
||||
word_count += 1;
|
||||
}
|
||||
} else {
|
||||
in_word = true;
|
||||
skip_ws = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
let str_line_count = format!("{line_count}");
|
||||
let str_word_count = format!("{word_count}");
|
||||
let str_byte_count = format!("{byte_count}");
|
||||
let align = max(
|
||||
str_line_count.len(),
|
||||
max(str_word_count.len(), str_byte_count.len()),
|
||||
);
|
||||
println!(
|
||||
"{:>align$} {:>align$} {:>align$} {filename}",
|
||||
str_line_count, str_word_count, str_byte_count
|
||||
);
|
||||
}
|
||||
|
||||
Loading…
Reference in New Issue
Block a user