Home
Head's Up: I'm in the middle of upgrading my site. Most things are in place, but there are something missing and/or broken including image alt text. Please bear with me while I'm getting things fixed.

Delete/Empty The Files Inside A Directory Recursively In Rust

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(())
}
results start

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.