这是检查一个目录是空的还是不是在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
为什么检查一个有很多文件的目录与只有一个文件的目录相比需要更长时间?
有没有更有效的方法来检查一个空目录,特别是如果它有1000个文件,如果不是空的
你写代码的方式不管它有多少文件(如果n> 2,你会break
)。 所以你的代码最多使用5个调用。 我不认为有什么办法(可移植)使其更快。
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; }
也许这个代码可以帮助你:
#include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { char cmd[1024]; char *folder = "/tmp"; int status, exitcode; if(argc == 2) folder = argv[1]; snprintf(cmd, 1024, "test $(ls -A \"%s\" 2>/dev/null | wc -l) -ne 0", folder); printf("executing: %s\n", cmd); status = system(cmd); exitcode = WEXITSTATUS(status); printf ("exit code: %d, exit status: %d\n", exitcode, status); if (exitcode == 1) printf("the folder is empty\n"); else printf("the folder is non empty\n"); return 0; }
我使用ls -A文件夹2> / dev / null |检查文件夹是否为空 wc -l,对文件夹中的文件进行计数,如果返回0则文件夹为空,否则该文件夹不为空。 WEXITSTATUS宏,返回执行命令的退出码。
注意:如果该文件夹不存在,或者您没有正确的权限来访问它,则该程序必须打印“文件夹为空”。