Alex Garella
9th October 2023
Listing the contents of a directory is a common task. Whether you're building a file manager or a system scanner, Rust provides efficient and straightforward ways to enumerate files in a directory. This blog post explains how to use Rust's standard library and the walkdir crate to achieve this.
Rust's std::fs
module provides the tools necessary for listing files in a directory.
use std::fs;
fn main() {
match fs::read_dir("/path/to/directory") {
Ok(entries) => {
for entry in entries {
match entry {
Ok(entry) => println!("{:?}", entry.path()),
Err(e) => eprintln!("Error: {}", e),
}
}
}
Err(e) => eprintln!("Error: {}", e),
}
}
Here, we use fs::read_dir
to obtain an iterator over the entries in a directory, printing each entry to the console.
walkdir
Crate:For a more feature-rich solution, the walkdir
crate provides additional functionalities like filtering and sorting.
walkdir
[dependencies]
walkdir = "2"
Add the above lines to your Cargo.toml
file to incorporate the walkdir
crate into your project.
extern crate walkdir;
use walkdir::WalkDir;
fn main() {
for entry in WalkDir::new("/path/to/directory") {
match entry {
Ok(entry) => println!("{}", entry.path().display()),
Err(e) => eprintln!("Error: {}", e),
}
}
}
With walkdir
, we can recursively list all files and directories, handling each entry as needed.
Listing files in a directory in Rust is a streamlined task, thanks to the std::fs
module and the walkdir
crate. By understanding and utilizing these resources, you can effectively manage filesystem operations in your Rust applications, making them more robust and capable.