如何仅计算路径中的目录数

时间:2016-04-27 17:28:26

标签: c file counting 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);
    }
    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;
}

2 个答案:

答案 0 :(得分:1)

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

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

<script type='text/javascript'>
    google.load('visualization', '1', {packages: ['corechart']});
</script>

<script type='text/javascript'>
    function drawVisualization() {
        var gdata = google.visualization.arrayToDataTable(['TurbTemp_F'], ['45.68'], ['45.68'], ['45.86'], ['45.86'], ['45.86'], ['45.86'], ['45.86'], ['45.86'], ['45.86'], ['45.5'], ['45.5'], ['45.68'], ['45.86'], ['45.86'], ['46.04'], ['46.22'], ['46.4'], ['46.58'], ['46.58'], ['46.76'], ['46.94'], ['47.12'], ['47.12'], ['47.3'], ['47.66'], ['47.66'], ['47.66'], ['47.84'], ['48.02'], ['48.02'], ['48.02'], ['48.2'], ['48.38'], ['48.74'], ['48.74'], ['48.92']);
        var options = {
            title: 'Title here',
            vAxis: { title: 'vvv' },
            seriesType: 'bars',
            series: {
                3: { type: 'area' }
            }
        };
        var chart = new google.visualization.ComboChart(document.getElementById('chart_div'));
        chart.draw(gdata, options);
    }
    google.setOnLoadCallback(drawVisualization);
</script>

答案 1 :(得分:0)

我想你想......

  • 用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; } 值。

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

如果您可以使用glob,则可以轻松计算目录数。那就是:main.c

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

您可以尝试这样:

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

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

public class items
{
    public string infoOne { get; set;}
    public string infoTwo { get; set;}
    public string infoFull
    {
        get { return $"{infoOne} {infoTwo}"; }
    }
}

感谢。