2013-04-01 26 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目录和父目录。它真的很棒。谢谢大家的帮助.. –