w3resource

Rust Function: Read file with Error handling

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

Write a Rust function that reads a file and prints its contents, handling file not found and permission errors.

Sample Solution:

Rust Code:

use std::fs; // Import the fs module for file handling

fn read_file(file_path: &str) {
    match fs::read_to_string(file_path) { // Attempt to read the file contents as a string
        Ok(contents) => { // If successful, print the file contents
            println!("File contents:");
            println!("{}", contents);
        }
        Err(error) => { // If an error occurs while reading the file
            match error.kind() { // Match on the type of error
                std::io::ErrorKind::NotFound => { // If file not found
                    println!("File not found: {}", file_path);
                }
                std::io::ErrorKind::PermissionDenied => { // If permission denied
                    println!("Permission denied to read file: {}", file_path);
                }
                _ => { // For other types of errors
                    println!("Error reading file {}: {}", file_path, error);
                }
            }
        }
    }
}

fn main() {
    let file_path1 = "test.txt"; // Specify the path of the text file
    let file_path2 = "example.txt"; // Specify the path of the text file
    let contents = "Rust Exercises!"; // Content to write to the file

    fs::write(file_path2, contents).expect("Failed to create file"); // Create the file with content

    read_file(file_path1); // Call the function to read and print the file contents
    read_file(file_path2); // Call the function to read and print the file contents
}

Output:

File not found: test.txt
File contents:
Rust Exercises!

Explanation:

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

  • The code imports the "fs" module from the standard library (std::fs) for file handling operations.
  • The "read_file()" function takes a file path (file_path: &str) as input and attempts to read the file's contents as a string using the "read_to_string()" function from the "fs" module.
  • Inside the "read_file()" function, it uses pattern matching ('match') to handle the 'Ok' and 'Err' cases:
    • If reading the file is successful ('Ok' variant), it prints the file contents.
    • If an error occurs while reading the file ('Err' variant), it further matches on the type of error:
      • If the error indicates that the file was not found ('NotFound' variant), it prints a corresponding message.
      • If the error indicates permission denied ('PermissionDenied' variant), it prints a corresponding message.
      • For any other type of error, it prints a generic error message.
  • In the main function:
    • It specifies two file paths ('file_path1' and 'file_path2') and the content to be written to 'file_path2'.
    • It uses the write function from the "fs" module to create the file specified by 'file_path2' with the specified content.
    • It then calls the "read_file()" function twice, passing 'file_path1' and 'file_path2' as arguments, respectively, to read and print the contents of the files.

Rust Code Editor:

Previous: Rust Program: Cube Root of user input.
Next: Rust Function: Read and Parse CSV 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.