Rust Function: Read file contents
Rust Result and Option types: Exercise-3 with Solution
Write a Rust function that reads a file and returns Result<String, std::io::Error>, where the string contains the file's contents.
Sample Solution:
Rust Code:
// Import the fs module from the standard library, which provides file system operations.
use std::fs;
// Import the io module from the standard library, which provides input/output functionality.
use std::io;
// Define a function named 'read_file_contents' that takes a file path as input and returns a Result<String, io::Error>.
fn read_file_contents(file_path: &str) -> Result<String, io::Error> {
// Use 'fs::read_to_string' to read the contents of the file specified by 'file_path' into a String.
match fs::read_to_string(file_path) {
// If reading the file is successful, return the contents wrapped in Ok.
Ok(contents) => Ok(contents),
// If an error occurs while reading the file, return the error wrapped in Err.
Err(error) => Err(error),
}
}
// Define the main function, where the program execution starts.
fn main() {
// Specify the file path of the file to be read.
let file_path = "example.txt"; // Adjust the file path as needed
// Call the `read_file_contents` function with the specified file path and handle the returned Result.
match read_file_contents(file_path) {
// If reading the file is successful, print its contents.
Ok(contents) => println!("File contents: {}", contents),
// If an error occurs while reading the file, print the error message.
Err(error) => eprintln!("Error reading file: {}", error),
}
}
Output:
Error reading file: No such file or directory (os error 2)
Explanation:
Here's a brief explanation of the above Rust code:
- Imports:
- use std::fs;: This imports the file system module from the standard library, allowing access to file-related functions.
- use std::io;: This imports the input/output module from the standard library, which provides types and functions for handling input and output operations.
- Function read_file_contents:
- This function takes a file path (&str) as input and returns a Result<String, io::Error>.
- It uses fs::read_to_string to read the contents of the file specified by the 'file_path' parameter.
- The 'match' statement handles the result of fs::read_to_string:
- If reading the file is successful (Ok(contents)), it returns the contents wrapped in 'Ok'.
- If an error occurs (Err(error)), it returns the error wrapped in 'Err'.
- Main function (main()):
- This is where the program execution starts.
- It specifies the file path of the file to be read ('example.txt' in this case).
- It calls the "read_file_contents()" function with the specified file path and handles the returned 'Result'.
- If reading the file is successful (Ok(contents)), it prints the file contents.
- If an error occurs while reading the file (Err(error)), it prints the error message.
Rust Code Editor:
Previous: Rust Function: Find maximum value.
Next: Rust Function: Square root calculation.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
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://w3resource.com/rust/error_handling/rust-result-and-option-types-exercise-3.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics