Walk directory tree - traverse the filesystem

walkdir

I needed this for the Rust Digger, but actually I bumped into the Walkdir crate totally by chance while I was looking for the crates with the biggest number of transitive reverse dependencies (popularity) on stats page of lib.rs. I saw memchr and looked at the looked at the GitHub Sponsors page of Andrew Gallant, the author of both.

Anyway, the crate has some very nice and clear examples and what you see here is basically the same, but I had to try it myself before I start using it in the application.

Dependency

examples/walk-directory-tree/Cargo.toml

[package]
name = "walk-directory-tree"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
walkdir = "2.5.0"

Code

examples/walk-directory-tree/src/main.rs

use walkdir::{DirEntry, WalkDir};

fn main() {
    let args = std::env::args().collect::<Vec<String>>();
    if args.len() != 2 {
        eprintln!("Usage: {} PATH", args[0]);
        std::process::exit(1);
    }
    let root = &args[1];

    // println!("{root}");

    // for entry in WalkDir::new(root) {
    //     let entry = entry.unwrap();
    //     println!("{}", entry.path().display());
    // }

    for entry in WalkDir::new(root).into_iter().filter_entry(skip_things) {
        let entry = entry.unwrap();
        println!("{}", entry.path().display());
    }
}

fn skip_things(entry: &DirEntry) -> bool {
    !entry
        .file_name()
        .to_str()
        .map(|name| entry.path().is_dir() && name == "target")
        .unwrap_or(false)
}

The first example, that is actually commented out in the code will traverse the whole tree starting from the root we provide.

for entry in WalkDir::new(root) {
    let entry = entry.unwrap();
    println!("{}", entry.path().display());
}

The second example will skip some things, specifically it will skip the "target" folder.

This is the output I get in the folder of the crate I used for the example:

$ cargo run -q .
.
./Cargo.lock
./Cargo.toml
./src
./src/main.rs

Related Pages

Disk usage: size of file or that of a directory tree using Rust

Author

Gabor Szabo (szabgab)

Gabor Szabo, the author of the Rust Maven web site maintains several Open source projects in Rust and while he still feels he has tons of new things to learn about Rust he already offers training courses in Rust and still teaches Python, Perl, git, GitHub, GitLab, CI, and testing.

Gabor Szabo