In Rust, listing all files in a directory can be achieved by using the std::fs and std::path modules. Specifically, the std::fs::read_dir function is used to read the directory contents. Here's a concrete example demonstrating how to list all files and directories within a specific directory in Rust:
rustuse std::fs; use std::path::Path; fn main() { // Set the directory to list files from let path = Path::new("."); // Use `read_dir` to read directory contents if let Ok(entries) = fs::read_dir(path) { for entry in entries { if let Ok(entry) = entry { // Get the path of the directory entry let path = entry.path(); if path.is_file() { // If it's a file, print the file path println!("File: {}", path.display()); } else if path.is_dir() { // If it's a directory, print the directory path println!("Dir: {}", path.display()); } } } } else { println!("Directory does not exist or is inaccessible"); } }
In this example, we first import the necessary modules. Then, within the main function, we specify the directory path to inspect. fs::read_dir retrieves the directory contents, returning a Result type that allows handling potential errors, such as when the directory is missing or inaccessible.
entries is an iterator containing information for each item in the directory. We iterate through this iterator, checking each item: if it's a file, we print the file path; if it's a directory, we print the directory path.
This program effectively lists all files and subdirectories in the specified directory while handling error cases. This approach ensures the code is robust and suitable for real-world applications.