Quick test if the directory is empty

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

Of course I can check the length

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

but this requires listing the entire contents of the directory, which I would prefer to avoid.

EDIT . I am looking for portable solutions.

EDIT ^ 2 : some timings for a huge directory (run this in a directory that is initially empty, it will create 100,000 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 switch -fis critical to ls, it will avoid the sorting that would otherwise occur.

+4
source share
1 answer

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

, "", dir , - :-(.

+2

Source: https://habr.com/ru/post/1525408/


All Articles