Crate walkdir

source ·
Expand description

Crate walkdir provides an efficient and cross platform implementation of recursive directory traversal. Several options are exposed to control iteration, such as whether to follow symbolic links (default off), limit the maximum number of simultaneous open file descriptors and the ability to efficiently skip descending into directories.

To use this crate, add walkdir as a dependency to your project’s Cargo.toml:

[dependencies]
walkdir = "2"

§From the top

The WalkDir type builds iterators. The DirEntry type describes values yielded by the iterator. Finally, the Error type is a small wrapper around std::io::Error with additional information, such as if a loop was detected while following symbolic links (not enabled by default).

§Example

The following code recursively iterates over the directory given and prints the path for each entry:

use walkdir::WalkDir;

for entry in WalkDir::new("foo") {
    println!("{}", entry?.path().display());
}

Or, if you’d like to iterate over all entries and ignore any errors that may arise, use filter_map. (e.g., This code below will silently skip directories that the owner of the running process does not have permission to access.)

use walkdir::WalkDir;

for entry in WalkDir::new("foo").into_iter().filter_map(|e| e.ok()) {
    println!("{}", entry.path().display());
}

The same code as above, except follow_links is enabled:

use walkdir::WalkDir;

for entry in WalkDir::new("foo").follow_links(true) {
    println!("{}", entry?.path().display());
}

§Example: skip hidden files and directories on unix

This uses the filter_entry iterator adapter to avoid yielding hidden files and directories efficiently (i.e. without recursing into hidden directories):

use walkdir::{DirEntry, WalkDir};

fn is_hidden(entry: &DirEntry) -> bool {
    entry.file_name()
         .to_str()
         .map(|s| s.starts_with("."))
         .unwrap_or(false)
}

let walker = WalkDir::new("foo").into_iter();
for entry in walker.filter_entry(|e| !is_hidden(e)) {
    println!("{}", entry?.path().display());
}

Structs§

  • A directory entry.
  • An error produced by recursively walking a directory.
  • A recursive directory iterator that skips entries.
  • An iterator for recursively descending into a directory.
  • A builder to create an iterator for recursively walking a directory.

Traits§

  • Unix-specific extension methods for walkdir::DirEntry

Type Aliases§

  • A result type for walkdir operations.