Search code examples
clinuxdirectory

Check if a directory is empty using C on Linux


Is this the right way of checking whether a directory is empty or not in C? Is there a more efficient way to check for an empty directory, especially if it has 1000s of files if not empty?

int isDirectoryEmpty(char *dirname) {
  int n = 0;
  struct dirent *d;
  DIR *dir = opendir(dirname);
  if (dir == NULL) //Not a directory or doesn't exist
    return 1;
  while ((d = readdir(dir)) != NULL) {
    if(++n > 2)
      break;
  }
  closedir(dir);
  if (n <= 2) //Directory Empty
    return 1;
  else
    return 0;
}

If its an empty directory, readdir will stop after the entries '.' and '..' and hence empty if n<=2.

If its empty or doesn't exist, it should return 1, else return 0

Update:

@c$ time ./isDirEmpty /fs/dir_with_1_file; time ./isDirEmpty /fs/dir_with_lots_of_files
0

real    0m0.007s
user    0m0.000s
sys 0m0.004s

0

real    0m0.016s
user    0m0.000s
sys 0m0.008s

Why does it take longer to check for a directory with lots of files as compared to one with just one file?


Solution

  • Is there a more efficient way to check for an empty directory, especially if it has 1000s of files if not empty

    The way you wrote your code it doesn't matter how many files it has (you break if n > 2). So your code is using a maximum of 5 calls. I don't think there's any way to (portably) make it faster.