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 .
单行检查目录是否可读且为空:
PathBuf::from("t").read_dir().map(|mut i| i.next().is_none()).unwrap_or(false);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.