【问题标题】:how can I get the number of directories in a directory?如何获取目录中的目录数?
【发布时间】:2013-04-01 20:30:34
【问题描述】:

我正在尝试获取文件夹中除文件之外的目录数,但我无法获得正确的结果。有人帮我解决这个问题吗?特别是我应该向 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);
}

【问题讨论】:

  • 你得到什么而不是“正确的结果”?
  • 将“dirp”传递给 isDirectory() 似乎是错误的。是不是打错字了?
  • 这条评论可能完全没有帮助,但看到这么多行代码用于概念性单行代码,我的眼睛很痛...ls -d <PATH>/*/ | wc -l
  • 正确结果表示目录数。我不想计算文件而是目录。

标签: c linux unix system


【解决方案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);

【讨论】:

  • Teppic 不起作用。当我按照你的方式时,我会得到当前目录中所有文件的数量。还有其他方法吗?
【解决方案2】:

对你的函数的调用是错误的。

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 服务器上对其进行了测试。而且效果很好。所以@teppic 是对的。但要注意,在代码中,目录的个数包括两个具体的“..”(父目录)和“.”。 (当前目录)。如果您不想包含它,您可以更改:

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

进入:

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

希望对你有帮助!

【讨论】:

  • 这就是重点,但我找不到应该发送给函数的内容。如何获取有关文件的信息?
  • 如果你真的需要调用函数int isDirectory(char *path),你可以这样做:isDirectory(direntp->d_name);
  • 哦,当然,Teppic 是对的 Shane。我忘记了 curr dir 和 parent dir 。它真的很好用。谢谢大家的帮助..
猜你喜欢
  • 2011-01-11
  • 2017-11-13
  • 1970-01-01
  • 2013-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-31
  • 1970-01-01
相关资源
最近更新 更多