How does one check a directory to see if it contains any files or folders? I've been searching for a solution and haven't found one that actually works. For instance, here's the code from one purported solution that is straightforward and easy to follow. I really like it but it doesn't work because it relies (like most other examples I found on the web) on the std::fs::read_dir()
function to throw an error.
use std::fs;
fn is_directory_empty(directory: &str) -> std::io::Result<bool> {
let mut entries = fs::read_dir(directory)?;
let first_entry = entries.next();
Ok(first_entry.is_none())
}
fn main() {
let directory = "/path/of/some/kind/";
match is_directory_empty(directory) {
Ok(is_empty) => {
if is_empty {
println!("{} is empty.", directory);
} else {
println!("{} is not empty.", directory);
}
}
Err(err) => {
println!("Error when checking if directory is empty: {}", err);
}
}
}
When I run this code on an empty directory it always matches to the Err
arm of the match statement. The read_dir()
function throws possible errors of several types, so it really doesn't help me know if the error was generated by a lack of content in the directory or something else. Is my thinking straight on this? Does anyone have some thoughts on how to solve this problem? Thanks.