home
NOTE: Under Construction - I'm in the middle of upgrading my site and lots of stuff is kinda broken. Please forgive the mess.

Delete/Empty The Files Inside A Directory Recursively In Rust

April 2024

This function empties a directory. Everything inside it is removed but the directory itself remains. Errors occur if the target directory doesn't exist or if something inside it can't be deleted.

Reminder

This code removes files recursively without asking for confirmation. Make sure to double check the path you're working on to make sure your code is pointing to the correct place.

Code
use std::fs;
use std::path::PathBuf;

fn main() {
  let target_dir = PathBuf::from("dir-to-empty");
  match empty_dir(&target_dir) {
    Ok(_) => println!("The directory was emptied"),
    Err(e) => println!("{}", e)
  }
}

fn empty_dir(dir: &PathBuf) -> std::io::Result<()> {
  for entry in dir.read_dir()? {
    let entry = entry?;
    let path = entry.path();
    if path.is_dir() {
      fs::remove_dir_all(path)?;
    } else {
      fs::remove_file(path)?;
    }
  };
  Ok(())
}
Results
The directory was emptied
═══ § ═══