Question

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.

Was it helpful?

Solution

You should make sure that:

  • You #include <dirent.h>, rather than "dirent.h", so that the system search path for headers is used to locate that file
  • You don't have a dirent.h file 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?

OTHER TIPS

I'm not sure, but it seems like I was always told that you always need a main function... However I have only a mere 8 months (2 semesters) of C++ under my belt. I just practice it to be safe, however, I would also use:

int main(int argc, char **argv) or int main(int argc, char *argv[]) rather than int logMaintenance(void *arg)

(while using dirent.h).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top