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?
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.
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.
The isDir() function is used to check a given file is a directory or not. Here we used stat() function and S_ISREG() macro.
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.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With