2013-04-01 27 views
0

我想獲得文件夾中的文件以外的目錄數量,但我無法獲得正確的結果。有人幫我解決這個問題?特別是我應該發送到isDirectory()函數?如何獲取目錄中的目錄數量?

int listFilesIndir(char *currDir) 
{ 
    struct dirent *direntp; 


    DIR *dirp; 
    int x ,y =0 ; 


    if ((dirp = opendir(currDir)) == NULL) 
    { 
     perror ("Failed to open directory"); 
     return 1; 
    } 

    while ((direntp = readdir(dirp)) != NULL) 
    { 
     printf("%s\n", direntp->d_name); 
     x= isDirectory(dirp); 
     if(x != 0) 
      y++; 
    } 
    printf("direc Num : %d\n",y); 

    while ((closedir(dirp) == -1) && (errno == EINTR)) ; 

    return 0; 
} 


int isDirectory(char *path) 
{ 
    struct stat statbuf; 

    if (stat(path, &statbuf) == -1) 
     return 0; 
    else 
     return S_ISDIR(statbuf.st_mode); 
} 
+1

你會得到什麼而不是「正確的結果」? – 2013-04-01 20:37:44

+0

將「dirp」傳遞給isDirectory()似乎是錯誤的。這是一個錯字嗎? – kkrambo

+1

這個評論可能是完全沒有幫助的,但它讓我的眼睛看到如此多的代碼行用於概念化的單行代碼...... ls -d /*/| wc -l' – shx2

回答

1

您正在向該函數發送一個目錄流,並將其視爲一個路徑。

Linux和其他一些Unix系統包括一種方式來獲得這些信息直接:

while ((direntp = readdir(dirp)) != NULL) 
{ 
    printf("%s\n", direntp->d_name); 
    if (direntp->d_type == DT_DIR) 
     y++; 
} 

否則,請確保您發送正確信息的功能,即

x= isDirectory(direntp->d_name); 
+0

它不工作Teppic。我按照自己的方式獲取當前目錄中所有文件的數量。有另一種方式嗎? –

+0

@Sabri - 我已經更新了答案。 – teppic

+0

謝謝Teppic。我很高興。你是對的.. –

1

的呼籲你的功能是錯誤的。

x= isDirectory(dirp); 

雖然函數的原型爲:

int isDirectory(char *path) 

它需要一個字符串作爲參數,但你給它一個 「DIR * dirp;」。我將代碼更改爲:

#include <stdio.h> 
#include <stdlib.h> 
#include <errno.h> 
#include <dirent.h> 
#include <sys/types.h> 
#include <sys/stat.h> 
#include <unistd.h> 

int listFilesIndir(char *currDir) 
{ 
    struct dirent *direntp; 


    DIR *dirp; 
    int x ,y =0 ; 


    if ((dirp = opendir(currDir)) == NULL) 
    { 
     perror ("Failed to open directory"); 
     return 1; 
    } 

    while ((direntp = readdir(dirp)) != NULL) 
    { 
     printf("%s\n", direntp->d_name); 
     if(direntp->d_type == DT_DIR) 
      y++; 
    } 
    printf("direc Num : %d\n",y); 

    while ((closedir(dirp) == -1) && (errno == EINTR)) ; 

    return 0; 
} 

int main(int argc, char **argv){ 
    if(argc == 2){ 
     // Check whether the argv[1] is a directory firstly. 
     listFilesIndir(argv[1]); 
    } 
    else{ 
     printf("Usage: %s directory", argv[0]);   
    } 
    return 0; 
} 

我在我的Linux服務器上測試了它。它運作良好。 SO @teppic是對的。但要注意,在代碼中,目錄的數量包括兩個特定的「..」(父目錄)和「。」。 (當前目錄)。如果你不想把它列入,你可以改變:

printf("direc Num : %d\n",y); 

到:

printf("direc Num : %d\n",y-2); 

希望它能幫助!

+0

這是重點,但我找不到我應該發送到該功能。我怎樣才能獲得有關文件的信息? –

+0

如果你真的需要調用函數int isDirectory(char * path),你可以這樣做:isDirectory(direntp-> d_name); – Sheng

+0

Ouh當然Teppic是正確的Shane。我忘了curr目錄和父目錄。它真的很棒。謝謝大家的幫助.. –