如何检查Rust中的目录是否为空?

jkm*_*ale 4 rust

我正在使用一个CLI工具,该工具可以避免用现有文件破坏现有目录,但不关心该目录不存在还是为空。

我知道我可以.exists()用来查看是否PathBuf指向现有文件/目录并.is_dir()查看它是否为目录,但是我将如何检查该目录是否为空?

Vas*_*kov 6

一行代码检查目录是否可读且为空:

PathBuf::from("t").read_dir().map(|mut i| i.next().is_none()).unwrap_or(false);
Run Code Online (Sandbox Code Playgroud)


小智 5

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();
Run Code Online (Sandbox Code Playgroud)

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.

  • 所以不允许 <6 个字符编辑 - 我认为应该是 `read_dir()?.next().is_none()` 是吗? (4认同)