Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would I check if a directory is empty in Rust?

Tags:

rust

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?

like image 446
jkmartindale Avatar asked Jun 24 '19 21:06

jkmartindale


2 Answers

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.

like image 104
miquels Avatar answered Nov 15 '22 11:11

miquels


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);
like image 30
VasiliNovikov Avatar answered Nov 15 '22 11:11

VasiliNovikov