w3resource

Rust Program: Count Lines in File with Error Handling

Rust Handling Errors with Result and Option: Exercise-4 with Solution

Write a Rust program that asks the user for a filename, reads the file, and counts the number of lines, handling I/O errors.

Sample Solution:

Rust Code:

use std::fs; // Import the fs module for file handling
use std::io; // Import the io module for user input and output

fn main() {

    let file_path2 = "test.txt"; // Specify the path of the text file
    let contents = "Rust Exercise1.\nRust Exercise2.\nRust Exercise3."; // Content to write to the file
    fs::write(file_path2, contents).expect("Failed to create file"); // Create the file with content
    
    println!("Input the filename:"); // Prompt the user to enter a filename

    let mut file_path = String::new(); // Declare a mutable variable to store the file path

    io::stdin() // Access stdin for user input
        .read_line(&mut file_path) // Read the user input and store it in file_path
        .expect("Failed to read input"); // Handle any potential I/O errors

    let file_path = file_path.trim(); // Remove leading and trailing whitespace from the file path

    let file_content = match fs::read_to_string(&file_path) { // Attempt to read the file contents
        Ok(content) => content, // If successful, store the file contents in file_content
        Err(error) => { // If an error occurs while reading the file
            eprintln!("Error reading file: {}", error); // Print an error message
            return; // Exit the program
        }
    };

    let num_lines = file_content.lines().count(); // Count the number of lines in the file content

    println!("Number of lines in the file: {}", num_lines); // Print the number of lines
} 

Output:

Input the filename:
Number of lines in the file: 3

Explanation:

Here's a brief explanation of the above Rust code:

  • It imports the "fs" module from the standard library for file handling and the "io" module for user input and output.
  • It creates a text file named "test.txt" with the specified content.
  • It prompts the user to input a filename.
  • It reads the user input and trims leading and trailing whitespace from the filename.
  • It attempts to read the contents of the file specified by the user input.
  • If the file is successfully read, it counts the number of lines in the file content.
  • It prints the number of lines in the file to the console.

Rust Code Editor:

Previous: Rust Function: Read and Parse CSV with Error handling.
Next: Rust Function: Safe Division with Error handling.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.