这是检查目录在C中是否为空的正确方法吗?有没有更有效的方法来检查空目录,特别是如果目录不为空则有1000个文件时?
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;
}
如果目录为空,则
readdir
将在条目“。”之后停止。和'..',如果是n<=2
,则为空。如果为空或不存在,则应返回1,否则返回0
更新:
@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
为什么检查包含大量文件的目录要比仅包含一个文件的目录花费更长的时间?
最佳答案
编写代码的方式与它有多少个文件无关(如果n> 2,则为break
)。因此,您的代码最多使用5个调用。我认为没有任何方法(可以方便地)使其更快。