I'm working on a CLI tool that avoids clobbering an existing directory with existing files but doesn't care if the directory doesn't exist or is empty.
I know I can use .exists()
to see if the PathBuf
points to an existing file/directory and .is_dir()
to see if it is a directory, but how would I check to see if the directory is empty?
You can use .read_dir()
to get an iterator over the entries of the directory. .
and ..
are skipped, so if the first next()
call on the iterator returns None
you know that the directory is empty.
let is_empty = dir_path_buf.read_dir()?.next().is_none();
If you are on Unix (POSIX, really) a different way to do this is to create a new temporary directory and try to rename it to the directory of the PathBuf
. The rename()
call, different from the mv
utility, will rename a directory if the target is non-existent or an empty directory.
One-liner to check if directory is readable and is empty:
PathBuf::from("t").read_dir().map(|mut i| i.next().is_none()).unwrap_or(false);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With