這是檢查目錄是否爲空或不在C中的正確方法嗎?有沒有更有效的方法來檢查空目錄,特別是如果它有1000個文件如果不是空的?使用Linux上的C檢查目錄是否爲空
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
爲什麼它需要更長的時間來檢查,有很多文件的目錄相比,到一個只有一個文件?
請閱讀我的編輯,爲什麼相同的代碼運行在有很多文件的目錄上的時間比只有一個文件的運行時間要長? – freethinker 2011-06-17 09:34:35
@freethinker我不確定。做一個'strace'並告訴我們。 – cnicutar 2011-06-17 09:36:46
添加了straces – freethinker 2011-06-17 09:50:08