W3cubDocs

/Rust

Function remove_dir_all

pub fn remove_dir_all<P: AsRef<Path>>(path: P) -> Result<()>

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

See the module-level TOCTOU explanation.

On most platforms, fs::remove_dir_all protects against symlink TOCTOU races by default. However, on the following platforms, this protection is not provided and the function should not be used in security-sensitive contexts:

  • 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(())
}

© 2010 The Rust Project Developers
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.
https://doc.rust-lang.org/std/fs/fn.remove_dir_all.html