Function remove_dir_all

1.0.0 · Source
pub fn remove_dir_all<P: AsRef<Path>>(path: P) -> Result<()>
Expand description

Removes a directory at this path, after removing all its contents. Use carefully!

This function does not follow symbolic links and it will simply remove the symbolic link itself.

§Platform-specific behavior

These implementation details may change in the future.

  • “Unix-like”: By default, this function currently corresponds to openat, fdopendir, unlinkat and lstat on Unix-family platforms, except where noted otherwise.
  • “Windows”: This function currently corresponds to CreateFileW, GetFileInformationByHandleEx, SetFileInformationByHandle, and NtCreateFile.

§Time-of-check to time-of-use (TOCTOU) race conditions

On a few platforms there is no way to remove a directory’s contents without following symlinks unless you perform a check and then operate on paths based on that directory. This allows concurrently-running code to replace the directory with a symlink after the check, causing a removal to instead operate on a path based on the symlink. This is a TOCTOU race. By default, fs::remove_dir_all protects against a symlink TOCTOU race on all platforms except the following. It should not be used in security-sensitive contexts on these platforms:

  • Miri: Even when emulating targets where the underlying implementation will protect against TOCTOU races, Miri will not do so.
  • Redox OS: This function does not protect against TOCTOU races, as Redox does not implement the required platform support to do so.

§Errors

See fs::remove_file and fs::remove_dir.

remove_dir_all will fail if remove_dir or remove_file fail on any constituent paths, including the root path. Consequently,

  • The directory you are deleting must exist, meaning that this function is not idempotent.
  • remove_dir_all will fail if the path is not a directory.

Consider ignoring the error if validating the removal is not required for your use case.

This function may return io::ErrorKind::DirectoryNotEmpty if the directory is concurrently written into, which typically indicates some contents were removed but not all. io::ErrorKind::NotFound is only returned if no removal occurs.

§Examples

use std::fs;

fn main() -> std::io::Result<()> {
    fs::remove_dir_all("/some/dir")?;
    Ok(())
}