Skip to content

Implementing a Command-Line Word Counter in Rust with Error Handling #1

Discussion options

You must be logged in to vote

Here's a complete Rust code example for a command-line application that reads a text file, counts the number of words, and handles potential errors gracefully:

use std::env;
use std::fs::File;
use std::io::{self, BufRead, BufReader};
use std::path::Path;

fn count_words(file_path: &str) -> Result<usize, io::Error> {
    let path = Path::new(file_path);
    let file = File::open(&path)?;
    let reader = BufReader::new(file);
    let mut word_count = 0;

    for line in reader.lines() {
        let line = line?;
        word_count += line.split_whitespace().count();
    }

    Ok(word_count)
}

fn main() {
    let args: Vec<String> = env::args().collect();
    if args.len() != 2 {
        …

Replies: 3 comments 1 reply

Comment options

You must be logged in to vote
1 reply
@0x001828
Comment options

Answer selected by BinaryBard0604
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants