Solution for Exercise 23-2

ex2302

#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);
    }
    while( (file = readdir(folder)) != NULL )
        printf("Found the file '%s'\n",file->d_name);
    closedir(folder);
    return(0);
}

Output

Found the file '.'
Found the file '..'
Found the file 'listing2305.c'
Found the file 'listing2301.c'
Found the file 'listing2306.c'
Found the file 'listing2302.c'
Found the file 'ex2301.c'
Found the file 'a.out'
Found the file 'listing2303.c'
Found the file 'ex2302.c'
Found the file 'listing2304.c'

Notes

* As long as the readdir() function returns a non-NULL pointer to a dirent structure (Line 16), the while loop spins and directory entries are read.

* The output above reflects the directory in which I run test programs for Chapter 23.