[erlang-questions] Best way to check if a given directory is empty (or not)?

Richard O'Keefe ok@REDACTED
Tue Mar 13 22:32:16 CET 2012


On 13/03/2012, at 9:51 PM, Richard Carlsson wrote:

> 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,

If you just want to know whether the directory is *empty* or not, it's simple and tolerably
fast at the C level:

	is_empty = 1;
	dirp = opendir("the directory");
	while ((entry = readdir(dirp)) != 0) {
	   if (0 != strcmp(entry->d_name, ".")
            && 0 != strcmp(entry->d_name, "..")
	   ) {
	      is_empty = 0;
              break;
	   }
	}
	closedir(dirp);

The OP's problem is that the Erlang libraries have nothing that mirrors
this interface exactly, only things to give you the result of a complete
scan.




More information about the erlang-questions mailing list