Rust System Calls and Error handling
Rust Error Propagation: Exercise-8 with Solution
Write a program that interacts with the operating system, performing system calls and handling errors.
Sample Solution:
Rust Code:
// Import necessary modules
use std::fs::File;
use std::io::{self, Write};
// Define a function to perform a system call and handle errors
fn perform_system_call() -> io::Resultlt;()> {
// Attempt to create a new file named "output.txt"
let mut file = File::create("output.txt")?;
// Write a message to the file
file.write_all(b"Hello, world!")?;
// Print a success message
println!("System call completed successfully.");
Ok(()) // Return Ok(()) to indicate success
}
// Define the main function
fn main() {
// Call the perform_system_call function and handle any errors
match perform_system_call() {
Ok(_) => println!("Program executed successfully."),
Err(err) => eprintln!("Error: {}", err),
}
}
Output:
System call completed successfully. Program executed successfully.
Explanation:
Here is a brief explanation of the above Rust code:
- Import the necessary modules: std::fs::File for file operations and std::io::{self, Write} for input/output operations.
- Define a function "perform_system_call()" to encapsulate the system call. It returns an io::Result<()>, where () indicates success and io::Error represents an error.
- Inside the function:
- Try to create a new file named "output.txt" using File::create("output.txt")?. The '?' operator is used for error propagation, which returns early with an error if the file creation fails.
- Write the message "Hello, world!" to the file using file.write_all(b"Hello, world!")?. Again, '?' is used for error propagation.
- If no errors occur, we print a success message to the console.
- In the main() function:
- Call the "perform_system_call()" function and handle any errors using pattern matching.
- If the system call completes successfully (Ok(_)), we print a success message.
- If an error occurs (Err(err)), we print the error message to the console.
Rust Code Editor:
Previous: Rust Complex Calculation Error handling.
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-error-propagation-exercise-8.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics