Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a directory is empty using C on Linux

Tags:

c

linux

directory

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?

like image 456
freethinker Avatar asked Jun 17 '11 09:06

freethinker


People also ask

How do I check if a directory is empty in Linux?

There are many ways to find out if a directory is empty or not under Linux and Unix bash shell. You can use the find command to list only files. In this example, find command will only print file name from /tmp. If there is no output, directory is empty.

How do I check if a directory is empty?

To check whether a directory is empty or not os. listdir() method is used. os. listdir() method of os module is used to get the list of all the files and directories in the specified directory.

How do you check if it is a file or directory in C?

The isDir() function is used to check a given file is a directory or not. Here we used stat() function and S_ISREG() macro.

How do I check if a directory is empty in C++?

static bool __fastcall IsEmpty(const System::UnicodeString Path); We can call IsEmpty to check whether a given directory is empty. An empty directory is considered to have no files or other directories in it. IsEmpty returns true if the directory is empty; false otherwise.


2 Answers

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.

like image 159
cnicutar Avatar answered Sep 18 '22 16:09

cnicutar


bool has_child(string path)
{
    if(!boost::filesystem::is_directory(path))
        return false;

    boost::filesystem::directory_iterator end_it;
    boost::filesystem::directory_iterator it(path);
    if(it == end_it)
        return false;
    else
        return true;
}
like image 33
Dawson Avatar answered Sep 17 '22 16:09

Dawson