home ~ projects ~ socials

Delete/Empty The Files Inside A Directory Recursively In Rust

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.

---
[dependencies]
anyhow = "1.0.98"
---

use anyhow::Result;
use std::fs;
use std::path::PathBuf;

fn main() -> Result<()> {
  let target_dir = PathBuf::from("dir-to-empty");
  empty_dir(&target_dir)?;
  println!("Done emptying directory");
  Ok(())
}

fn empty_dir(dir: &PathBuf) -> Result<()> {
  if let Ok(exists) = dir.try_exists() {
    if exists {
      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(())
}
Output:
Done emptying directory
-- end of line --