Home
| Colors: |
May 2023

Process A Directory Recursitvely In Rust

This is a stright copy from The Rust Cookbookrcb. It hits all files that aren't hidden (i.e. that don't start with a .)

use walkdir::{DirEntry, WalkDir};

fn is_not_hidden(entry: &DirEntry) -> bool {
    entry
        .file_name()
        .to_str()
        .map(|s| entry.depth() == 0 || !s.starts_with("."))
        .unwrap_or(false)
}

fn main() {
    WalkDir::new(".")
        .into_iter()
        .filter_entry(|e| is_not_hidden(e))
        .filter_map(|v| v.ok())
        .for_each(|x| println!("{}", x.path().display()));
}

You can also do this format, but I kinda like the inline iterator approach.

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