【问题标题】:Finding number of Files and Folders In Directory查找目录中文件和文件夹的数量
【发布时间】:2020-10-07 13:24:39
【问题描述】:

我必须找出一个目录中有多少个文件夹和多少个常规文件。 我尝试了一些东西,但我什至无法编译我的代码。我什至不知道我的程序是否正确。当我尝试编译我的代码时,有两种错误。其中一个是错误:struct dirent has no member named 'd_type' and 'DT_DIR' undeclared(first use in this function, DT_REG undeclared(first use in this function).

如果错误与我的编译器有关,我正在将 CodeBlocks 与 MinGW 一起使用;我必须使用这个 IDE。

如何修复我的代码?

#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>

int
main(int argc, char *argv[])
{
    int file_count = 0;
    int dir_count = 0;
    struct dirent * entry;
    DIR *dp;

    if (argc != 2)
    {
        printf("usage: give directory_name\n");
        exit(-1);
    }

    if ((dp = opendir(argv[1])) == NULL)
    {
        printf("Error: can't open %s\n", argv[1]);
        exit(-2);
    }
    while ((entry= readdir(dp)) != NULL){

        if (entry->d_type == DT_REG)
         file_count++;

        else if (entry->d_type == DT_DIR)
         dir_count++;
    }

    closedir(dp);

    printf(" %d Number of file ", file_count);
    printf(" %d Number of folders", dir_count);
    exit(0);
}

【问题讨论】:

  • 我不知道这是否是导致您的问题的原因,但看起来我们在您的探测开始时缺少您的一些 #include 指令。你能检查你的代码并编辑你的问题吗?谢谢!
  • 其实include库是没有错的。我都做了。 #include ,, , , 但他们没有出现在这里我犯了一个错误,而我'我发布我的代码。

标签: c file-io directory gnu


【解决方案1】:

也许您缺少一些包含?

这是我的版本

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

int main(int argc, char *argv[]) {
    DIR *dir;
    struct dirent *ent;

    size_t nfiles = 0, ndirs = 0;

    if (argc != 2) {
        fprintf(stderr, "Usage: %s directory\n", argv[0]);
        return -1;
    }

    if (!(dir = opendir(argv[1]))) {
        fprintf(stderr, "[!] Could not open directory `%s': %s\n", argv[1],
                strerror(errno));
        return -2;
    }

    while ((ent = readdir(dir))) {
        // Ignore . and .. entries
        if (!strcmp(ent->d_name, ".") || !strcmp(ent->d_name, "..")) {
            continue;
        }

        if (ent->d_type == DT_REG) {
            ++nfiles;
        } else if (ent->d_type == DT_DIR) {
            ++ndirs;
        }
    }

    closedir(dir);
    printf("%lu Files, %lu Directories\n", nfiles, ndirs);

    return 0;
}

【讨论】:

  • if (ent->d_type == DT_REG) { 这行给出:'struct dirent'没有名为'd_type'的成员,并且DT_REG未在此范围内声明。 } else if (ent->d_type == DT_DIR) { 这行给出:'struct dirent' 没有名为 'd_type' 的成员,并且 DT_DIR 未在此范围内声明。
  • 你的操作系统和编译器是什么?
  • 我的操作系统是 Windows。我的编译器是 CodeBlocks,但我也尝试过 DevC++。
  • 您尝试使用的函数是 POSIX 函数。它们可能在 Windows 等非 posix 兼容的操作系统中不可用..
  • 我想问你另一个密码。我该怎么做?
猜你喜欢
  • 1970-01-01
  • 2020-10-07
  • 1970-01-01
  • 2013-03-19
  • 2014-08-13
  • 1970-01-01
  • 1970-01-01
  • 2012-11-12
  • 1970-01-01
相关资源
最近更新 更多