[erlang-questions] Best way to check if a given directory is empty (or not)?
Tue Mar 13 09:51:30 CET 2012
On 03/13/2012 07:09 AM, Zabrane Mickael wrote:
> Hi guys,
> I'd like to know if there's a good and portable method to check if a directory is empty (or not)?
> In my case, the directory can contains huge number (more than 150K in average) of files if it is not empty.
> I've tested the following working calls:
> a. file:list_dir/1
> b. filelib:wildcard/2
> The problem with them is they both return a list of filenames.
> I'd like to avoid getting this list back to be able to check if it's empty or not.
I don't think it can be done. E.g., looking at the POSIX interface
towards directories, a directory is treated as a sequence of names and
corresponding inode numbers. There is no function for getting the number
of entries of a directory, and I assume that in many file systems the
directory size is simply never stored explicitly. The only portable
method is to get the list of entries and count them yourself, i.e.,
In my experience, file systems may _handle_ 100K+ files in directories,
and opening individual files may work fine when you know their exact
names, but reading the whole directory list can be slow, and if you need
to traverse all the inodes to check time stamps or similar, you might as
well go for lunch.
More information about the erlang-questions