Skip to navigation
How to List Files in a Directory in Rust
27.11.25
https://rustjobs.dev/blog/how-to-list-files-in-a-directory-in-rust/Basic Directory Listing: 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. Exploring the walkdir Crate: For a more feature-rich solution, the walkdir crate provides additional functionalities like filtering and sorting. 1. Installing walkdir [dependencies] walkdir = "2" Add the above lines to your Cargo.toml file to incorporate the walkdir crate into your project. 2. Recursive Directory Listing: 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), } } } ```
https://rustjobs.dev/blog/how-to-list-files-in-a-directory-in-rust/
Reply
Anonymous
Information Epoch 1770537574
Small is beautiful.
Home
Notebook
Contact us