DEV Community

Nathan
Nathan

Posted on • Originally published at natclark.com

List All Files in a Directory Using Rust

Rust has a very useful built-in file system module. The following code uses it to print each file in a given directory:

use std::fs;

fn main() {
    for file in fs::read_dir("./change_this_path").unwrap() {
        println!("{}", file.unwrap().path().display());
    }
}
Enter fullscreen mode Exit fullscreen mode

Recursively crawling directories

But for solutions that are a little more advanced, I recommend using a lightweight crate called walkdir.

First, you'll need to add the following two lines to your Cargo.toml:

[dependencies]
walkdir = "2"
Enter fullscreen mode Exit fullscreen mode

Then, you'll need to install it with the following command:

cargo install --path .
Enter fullscreen mode Exit fullscreen mode

We can use walkdir to recursively crawl all the files in a directory.

In other words, we can list all the files in a directory, all the files in each subdirectory, all the files in each subdirectory's subdirectory, and so on:

extern crate walkdir;
use walkdir::WalkDir;

fn main() {
    for file in WalkDir::new("./change_this_path").into_iter().filter_map(|file| file.ok()) {
        println!("{}", file.path().display());
    }
}
Enter fullscreen mode Exit fullscreen mode

However, folders are still included in the list.

Listing files but not folders

Here's an example of walkdir in action with a script that has the same functionality as before, except folders are excluded:

extern crate walkdir;
use walkdir::WalkDir;

fn main() {
    for file in WalkDir::new("./change_this_path").into_iter().filter_map(|file| file.ok()) {
        if file.metadata().unwrap().is_file() {
            println!("{}", file.path().display());
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Counting the files in a directory

And if you just want to count the number of files in a directory, the count() method is your friend:

use std::fs;
extern crate walkdir;
use walkdir::WalkDir;

fn main() {
    // Count all files and folders in directory:
    println!("{}", fs::read_dir("./change_this_path").unwrap().count());
    // Recursively count all files and folders in directory and subdirectories:
    println!("{}", WalkDir::new("./change_this_path").into_iter().count());
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

Working with files in Rust can be easy and fun, especially when using a handy crate like walkdir.

And when dealing with larger file systems, Rust's incredible performance really starts to shine.

I hope you enjoyed these snippets! This is my first Rust tutorial on this blog, but I look forward to writing more.

Top comments (0)