I wrote a barebones version of wc
in rust. wc
is a program that counts the number of characters, words, and lines in a file and outputs those values to the command line. Here is an example of the output:
9 25 246 Cargo.toml
52 163 1284 src/main.rs
61 188 1530 total
My version currently lacks the proper output alignment, and it doesn't print the total (it also lacks the command line options, and it panics when fed a directory). But I would like to get some feedback before I go any further.
use std::env;
use std::fs::read_to_string;
struct InputFile {
words: u32,
lines: u32,
characters: u32,
name: String,
}
impl InputFile {
fn new(name: &String) -> Self {
let content = read_to_string(name).unwrap();
let (mut characters, mut words, mut lines) = (0, 0, 0);
let mut spaced: bool = false;
for c in content.chars() {
if c as u8 != 0 {
characters += 1;
}
if c != ' ' && c != '\n' {
spaced = false
}
if c == '\n' {
lines += 1;
if !spaced {
words += 1;
spaced = true;
}
}
if c == ' ' && !spaced {
words += 1;
spaced = true;
}
}
Self { lines, words, characters, name: name.to_string() }
}
}
impl std::fmt::Display for InputFile {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{} {} {} {}",
self.lines, self.words, self.characters, self.name
)
}
}
fn main() {
let files: Vec<String> = env::args().collect();
for f in &files[1..] {
println!("{}", InputFile::new(f));
}
}