首页 文章

获取目录中的文件列表

提问于
浏览
3

我正在开发一个C项目,我需要获取目录中的文件列表 . 我正在使用dirent.h但是在使用它时遇到了一些问题,我正在Linux下构建程序 .

当我尝试构建程序时,我收到以下错误

myClass:error: âDIRâ undeclared (first use in this function)
myClass:408: error: (Each undeclared identifier is reported only once
myClass:408: error: for each function it appears in.)
myClass:408: error: âdirâ undeclared (first use in this function)
myClass:410: warning: implicit declaration of function âopendirâ
myClass:413: warning: implicit declaration of function âreaddirâ
myClass:413: warning: assignment makes pointer from integer without a cast
myClass:415: error: dereferencing pointer to incomplete type
myClass:417: warning: implicit declaration of function âclosedirâ

下面是我正在使用的代码

int logMaintenance(void *arg)
{
    DIR *dir;
    struct dirent *ent;
    dir = opendir(directory);
    if (dir != NULL)
    {
        while ((ent = readdir (dir)) != NULL)
        {
            printf("%s\n", ent->d_name);
        }
        closedir(dir);
    }
    else
    {
        printf("Failed to read directory %i", EXIT_FAILURE);
    }
    return 0;
}

我不明白这些错误是什么意思,特别是当我说我已经包含了针对Liunux的dirent.h头文件时DIR是未声明的 .

谢谢你的帮助 .

2 回答

  • 3

    你应该确保:

    • #include <dirent.h> ,而不是 "dirent.h" ,以便使用 Headers 的系统搜索路径来查找该文件

    • 您的项目中某处没有 dirent.h 文件,而是可以取而代之的 .

    在尝试调试此类奇怪问题时,请向GCC询问 gcc -E 的预处理输出 . 您可以看到它包含的文件(包括路径) . 这可以帮到很多 .

    如果您使用的是Microsoft Visual Studio,请转到此问题:
    Microsoft Visual Studio: opendir() and readdir(), how?

  • 0

    我不确定,但似乎总是被告知你总是需要一个主要的功能...但是我只有8个月(2个学期)的C . 我只是练习它是安全的,但是,我也会使用:

    int main(int argc, char **argv)int main(int argc, char *argv[]) 而不是 int logMaintenance(void *arg)

    (使用dirent.h时) .

相关问题