这是在 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
为什么检查包含大量文件的目录比检查只有一个文件的目录花费的时间更长?
最佳答案
Is there a more efficient way to check for an empty directory, especially if it has 1000s of files if not empty
您编写代码的方式与它有多少文件无关(如果 n > 2,您将中断
)。所以您的代码最多使用 5 次调用。我不认为有任何方法可以(便携地)让它更快。
关于在 Linux 上使用 C 检查目录是否为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6383584/