2011-06-17 110 views
13

這是檢查目錄是否爲空或不在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 

爲什麼它需要更長的時間來檢查,有很多文件的目錄相比,到一個只有一個文件?

回答

8

是否有檢查 一個空目錄更有效的方式,特別是如果 有文件,如果不爲空

你寫代碼的方式也沒關係多少1000它有文件(如果n> 2,則爲break)。所以你的代碼最多使用5次調用。我不認爲有什麼辦法可以(可移植地)使其更快。

+0

請閱讀我的編輯,爲什麼相同的代碼運行在有很多文件的目錄上的時間比只有一個文件的運行時間要長? – freethinker 2011-06-17 09:34:35

+0

@freethinker我不確定。做一個'strace'並告訴我們。 – cnicutar 2011-06-17 09:36:46

+0

添加了straces – freethinker 2011-06-17 09:50:08

3
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; 
} 
+1

@freethinker在C中編碼。Bools在C中不存在,除非你用類似於'typedef enum {false,true} bool;'的方式定義它們。 – Larrimus 2017-02-05 19:34:40

0

也許這個代碼可以幫助你:

#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,對文件夾中的文件進行計數,如果返回零,則文件夾爲空,否則該文件夾不爲空。 WEXITSTATUS宏返回執行命令的退出代碼。

注意:如果該文件夾不存在,或者您沒有正確的權限來訪問它,該程序必須打印「文件夾爲空」。