w3resource

Rust File Processing Function: Read, Process, and Write with Error Handling

Rust Error Propagation: Exercise-1 with Solution

Write a Rust function that reads a file, processes its contents, and writes to another file, propagating any errors.

Sample Solution:

Rust Code:

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

// Function to read a file, process its contents, and write to another file
fn process_file(input_file: &str, output_file: &str) -> Result<(), io::Error> {
    // Read the contents of the input file
    let file_content = fs::read_to_string(input_file)?;

    // Process the contents as needed (example: convert to uppercase)
    let processed_content = file_content.to_uppercase();

    // Write the processed content to the output file
    fs::write(output_file, processed_content)?;

    Ok(()) // Return Ok if the operation completes successfully
}

fn main() -> Result<(), io::Error> {
    let input_file = "input.txt"; // Specify the path of the input file
    let contents = "Rust Exercises!"; // Content to write to the file
    fs::write(input_file, contents).expect("Failed to create file"); // Create the file with content

    let output_file = "output.txt"; // Specify the path of the output file

    // Call the function to process the file
    process_file(input_file, output_file)?;

    println!("File processed successfully."); // Print a success message

    Ok(()) // Return Ok if the program completes successfully
}

Output:

File processed successfully.

Explanation:

Here is a brief explanation of the above Rust code:

  • use std::fs; and use std::io;: These lines import the "fs" module for file handling and the "io" module for file I/O operations.
  • fn process_file(input_file: &str, output_file: &str) -> Result<(), io::Error> {: This line declares a function named "process_file()" that takes two arguments: 'input_file' and 'output_file', both of type &str. The function returns a 'Result' indicating success (Ok(())) or an error (Err(io::Error)).
  • let file_content = fs::read_to_string(input_file)?;: This line reads the contents of the input file specified by 'input_file' into a String. The ? operator is used to propagate any errors that occur during file reading.
  • let processed_content = file_content.to_uppercase();: This line converts the contents of file_content to uppercase using the to_uppercase() method.
  • fs::write(output_file, processed_content)?;: This line writes the 'processed_content' to the output file specified by 'output_file'. Again, the ? operator is used to propagate any errors during file writing.
  • fn main() -> Result<(), io::Error> {: This line declares the "main()" function, which also returns a 'Result' indicating success or failure.
  • fs::write(input_file, contents).expect("Failed to create file");: This line creates an input file named "input.txt" with the content "Rust Exercises!".
  • let output_file = "output.txt";: This line specifies the name of the output file as output.txt.
  • process_file(input_file, output_file)?;: This line calls the "process_file()" function to process the input file and write the processed content to the output file. The ? operator is used to propagate errors.
  • println!("File processed successfully.");: This line prints a success message if the program completes without errors.
  • Ok(()): Finally, the function returns Ok(()) to indicate that the program executed successfully. If any error occurs during file processing or I/O operations, it will be returned as an Err(io::Error) type.

Rust Code Editor:

Previous: Rust Error Propagation Exercises.
Next: Rust File Operations: Copy, Move, Delete with Error handling.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/rust/error_handling/rust-error-propagation-exercise-1.php