【问题标题】:How to count only the number of directories from a path如何仅计算路径中的目录数
【发布时间】:2016-08-22 03:59:03
【问题描述】:

我试图只计算路径中的目录,但它不起作用。所以,我不想同时给文件和目录编号,我只想要目录。请问你能帮帮我吗? 代码:

int listdir(char *dir) {
    struct dirent *dp;
    struct stat s;
    DIR *fd;
    int count = 0;

    if ((fd = opendir(dir)) == NULL) {
        fprintf(stderr, "listdir: can't open %s\n", dir);
    }
    while ((dp = readdir(fd)) != NULL) {
        if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
            continue;
        stat(dp->d_name, &s);
        if (S_ISDIR(s.st_mode))
        count++;
    }
    closedir(fd);
    return count;
}

【问题讨论】:

  • 使用S_ISREG() 来判断目录条目是否为常规文件,否则为目录(或链接)。
  • 不行……

标签: c file counting stat


【解决方案1】:

您的 stat() 调用将失败,因为您不在正确的目录中。您可以通过更改当前目录或生成完整路径并将 stat 作为参数来解决此问题。

某些 Unix,您可以通过查看 struct dirent、d_type 字段来优化 stat 调用

int listdir(char *dir) {
    struct dirent *dp;
    struct stat s;
    DIR *fd;
    int count = 0;

    if ((fd = opendir(dir)) == NULL) {
        fprintf(stderr, "listdir: can't open %s\n", dir);
    }
    chdir (dir); /* needed for stat to work */
    while ((dp = readdir(fd)) != NULL) {
        if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
            continue;
#ifdef _DIRENT_HAVE_D_TYPE
        switch (dp->d_type)
        {
          case DT_UNKNOWN:
            stat(dp->d_name, &s);
            if (S_ISDIR(s.st_mode)) count++;
            break;
          case DT_DIR:
            count++;
            break;
        }
#else
        stat(dp->d_name, &s);
        if (S_ISDIR(s.st_mode)) count++;
#endif            
    }
    closedir(fd);
    return count;
}

【讨论】:

【解决方案2】:

我想你想要...

  • 用 C 编写
  • 计算路径中的目录数。
  • 计数函数将返回int值。

我不了解您的环境,所以这只是一个示例解决方案。

如果你可以使用glob,那么计算目录数量就很容易了。即:main.c

#include <stdio.h>
#include <glob.h>
#include <string.h>

#define MAX_PATH 1023

int countDirectories(char* dir)
{
    char path[MAX_PATH] = "";
    strcat(path, dir);
    strcat(path, "/*");

    glob_t globbuf;
    long i, count = 0;

    if (glob(path, GLOB_NOSORT | GLOB_ONLYDIR, NULL, &globbuf) == 0)
    {
        count = globbuf.gl_pathc;
        for (i = 0; i < globbuf.gl_pathc; i++)
        {
            count += countDirectories(globbuf.gl_pathv[i]);
        }
    }
    globfree(&globbuf);

    return count;
}

int main(int argc, char* argv[])
{
    int count;

    if (argc > 1)
    {
        count = countDirectories(argv[1]);
    }
    else
    {
        count = countDirectories(".");
    }

    printf("there are %d directories.\n", count);

    return 0;
}

你可以试试这个:

> gcc main.c -o testglob
> ./testglob /path/to/target/dir

然后你会收到这样的输出:

path = /path/to/target/dir/*, there are N directories

谢谢。

【讨论】:

  • edited:) 你可以使用我的countDirectories 作为你的listdir 函数。 glob 是按 pattern 搜索文件/目录的函数。并使用标志GLOB_ONLYDIR,我们只能搜索目录。因此,您可以在path 中找到目录数。
猜你喜欢
  • 2011-11-02
  • 2020-07-16
  • 1970-01-01
  • 2016-05-16
  • 1970-01-01
  • 2019-03-07
  • 1970-01-01
  • 2012-01-26
  • 2021-08-02
相关资源
最近更新 更多