I am working on a C project where I need to get the list of files that are within a directory. I am using dirent.h but am having some problems getting it to work, I am building the program under Linux.
When I try and build the program I get the following error
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â
Below is the code that I am using
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;
}
I don’t understand what these errors mean especially when it says that DIR is undeclared when I have included the dirent.h header file for Liunux.
Thanks for your help.
You should make sure that:
#include <dirent.h>, rather than"dirent.h", so that the system search path for headers is used to locate that filedirent.hfile lying around somewhere in your project that could be picked up instead.When trying to debug this type of strange problem, ask GCC for the pre-processed output with
gcc -E. You can see what files (including the paths) it’s including. That can help a lot.And if you’re using Microsoft Visual Studio, head over to this question:
Microsoft Visual Studio: opendir() and readdir(), how?