home ~ projects ~ socials

Do A Glob Search For Files In A Directory With Rust

Basic Recursive Glob

//! ```cargo
//! [dependencies]
//! glob = "0.3.1"
//! ```


use glob::glob;

fn main() {
    for entry in glob("recursive_test/**/*.txt").expect("Failed to read glob pattern") {
        match entry {
            Ok(path) => println!("{:?}", path.display()),
            Err(e) => println!("{:?}", e),
        }
    }
}
Output:
"recursive_test/example/.hidden_file_1.txt"
"recursive_test/example/.hidden_file_2.txt"
"recursive_test/example/1.txt"
"recursive_test/example/a/2.txt"
"recursive_test/example/a/c/4.txt"
"recursive_test/example/b/3.txt"

The code uses the anyhow and glob crates which can be installed with:

cargo add anyhow cargo add glob

-- end of line --

References

  • Process A Directory Recursitvely In Rust

    An alternative method for processing all the files and diretories directly instead of via the glob filtered set.