Delete File in Rust
Rust Programming Language
Problem
Rust program that deletes a file from the file system.
Input
use std::fs;fn main() -> std::io::Result<()> {let filename = "file_to_delete.txt";fs::remove_file(filename)?;println!("File {} has been deleted successfully.", filename);Ok(())}{codeBox}
Output
File file_to_delete.txt has been deleted successfully.{codeBox}
Explanation
This program uses the std::fs::remove_file function to delete the file specified by the filename variable. If the file is successfully deleted, the program prints a success message to the console. Note that you will need to replace "file_to_delete.txt" with the name of the file you want to delete.
The remove_file function returns a std::io::Result<()>, which is an empty Ok(()) value if the file is successfully deleted. If an error occurs, such as if the file does not exist or if the user does not have permissions to delete the file, the function returns an Err variant with an error message.
If you want to delete a non-empty directory, you can use the std::fs::remove_dir_all function instead, which recursively deletes all files and subdirectories within the directory.