Solution for Exercise 23-1

ex2301

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

int main()
{
    DIR *folder;
    struct dirent *file;

    folder=opendir(".");
    if(folder==NULL)
    {
        puts("Unable to read directory");
        exit(1);
    }
    file = readdir(folder);
    printf("Found the file '%s'\n",file->d_name);
    closedir(folder);
    return(0);
}

Output

Found the file '.'

Notes

* The reason this code provides no risk is that the first "file" listed in every directory is the directory itself, represented as the single dot shown in the output (and referenced at Line 10 in the code).

* I thought about listing the dirent structure in the book, but it's really boring. If you want to see how it looks, examine the dirent.h file on your computer. Be aware that dirent.h may itself include other header files that could contain the actual structure definition.