Rust Lang

How to Delete Files in Rust

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:

pub fn remove_file<P: AsRef<Path>>(path: P)

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:

  1. Lack of file permissions when removing the file
  2. If the provided path is a directory
  3. 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:

use std::fs;
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:

$ cargo run
   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:

use std::fs;
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.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list