获取目录中的文件列表

时间:2012-04-30 13:09:46

标签: c dirent.h

我正在开发一个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 个答案:

答案 0 :(得分:3)

你应该确保:

  • #include <dirent.h>,而不是"dirent.h",以便使用标头的系统搜索路径来查找该文件
  • 您的项目中某处没有dirent.h文件,而是可以取而代之。

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

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

答案 1 :(得分:0)

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

int main(int argc, char **argv)int main(int argc, char *argv[])而非。{ int logMaintenance(void *arg)

(使用dirent.h时)。