Delete All The Files Inside A Directory Recursively In Rust

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.

rust

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(())
}
            
The directory was emptied
        

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.