Fast test if directory is empty

自古美人都是妖i 提交于 2019-12-18 21:48:28

问题


What is the fastest way to test if a directory is empty?

Of course I can check the length of

list.files(path, all.files = TRUE, include.dirs = TRUE, no.. = TRUE)

but this requires enumerating the entire contents of the directory which I'd rather avoid.

EDIT: I'm looking for portable solutions.

EDIT^2: Some timings for a huge directory (run this in a directory that's initially empty, it will create 100000 empty files):

system.time(file.create(as.character(0:99999)))
#    user  system elapsed 
#   0.720  12.223  14.948 
system.time(length(dir()))
#    user  system elapsed 
#   2.419   0.600   3.167 
system.time(system("ls | head -n 1"))
# 0
#   user  system elapsed 
#  0.788   0.495   1.312 
system.time(system("ls -f | head -n 3"))
# .
# ..
# 99064
#    user  system elapsed 
#   0.002   0.015   0.019 

The -f switch is crucial for ls, it will avoid the sorting that will take place otherwise.


回答1:


How about if(length(dir(all.files=TRUE)) ==0) ?

I'm not sure what you qualify as "fast," but if dir takes a long time, someone is abusing your filesystem :-(.



来源:https://stackoverflow.com/questions/21576944/fast-test-if-directory-is-empty

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!