Deleting files is very common in computing. It can be crucial, as programmers continuously monitor and remove files within a directory.
In this guide, we will discuss how you can delete files from the filesystem using the Rust programming language.
Rust Remove File Function
To delete a file in Rust, we use the remove_file from the fs modules provided by the Rust standard library.
The following function syntax is shown below:
The function accepts the path to the file within the filesystem as a string. Then, it removes the file from the system and returns an error if encountered.
Potential causes of an error when using the function include:
- Lack of file permissions when removing the file
- If the provided path is a directory
- Provided file does not exist in the path
Rust Remove File Example
The following program illustrates how to use the remove_file function to delete a file in Rust:
fn main() {
fs::remove_file("me.txt")
.expect("File delete failed");
println!("File deleted successfully!");
}
The previous program attempts to remove the file me.txt in the current working directory. If the function encounters an error, we print the message to the user, showing that file deletion failed.
Otherwise, remove the file and print a success message for the user. Running the previous code should return a message as:
Finished dev [unoptimized + debuginfo] target(s) in 0.00s
Running `delete_file.exe`
File deleted successfully!
Rust Delete Directory
Suppose you want to remove all the files within a directory. You can do this using the remove_dir function. The function behaves similarly to the remove_file function. However, it removes an entire directory.
An example usage is as shown:
fn main() {
fs::remove_dir("delete_me")
.expect("Error removing directory");
println!("Directory removed successfully!");
}
The previous program removes the directory in the specified path and returns the message.
Conclusion
This beginner-friendly guide walks you through the process of removing a file and directory using the Rust programming language. This process includes the Rust remove file function, the Rust remove file example, and the Rust delete directory. We hope you found this article helpful. Check the other Linux Hint articles for more tips and information.