Checking a directory to see if it is empty

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.

The errors are I/O errors: things like the path being unreadable because the user doesn't have permissions, or it's on a network share that has connectivity issues. Situations that are literally erroneous. "This directory is empty" is not an error case. That just returns an empty iterator.

I guess you might be trying to check a path that doesn't exist. That would be an erroneous situation. There is no path to iterate in that case. It would return an error with ErrorKind::NotFound or similar. If you need to handle these in your app logic, it's reachable through err.kind().

For your more specific question, I'm afraid I won't be much help. I don't think I've ever had a need to check that a directory is empty, and I would worry about TOCTOU bugs if I did.

5 Likes

And now I'm embarrassed. The empty folder was named Empty rather than empty. All just a matter of a capital letter. Sorry to have bothered you. :flushed: :anguished:

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.