Reading a Directory's Contents
Before you can view the files in a directory you need to open it.
<dirent.h> declares the following functions for opening, reading, closing, and rewinding a directory.
To open a directory, use opendir():
DIR * opendir(const char * pathname);
This function returns a pointer to a
DIR data structure that represents a directory. A NULL value indicates an error.
pathname must be a name of an existing directory.
After opening a directory, use readdir() to traverse it:
struct dirent * readdir (DIR * pdir);
pdir is the result of a previous
opendir() call.
readdir() returns a pointer to a
dirent structure whose member
d_name contains the name of the current file (the rest of
dirent's members depend on the specific file system installed on your computer). Each successive call advances to the next file in the directory. There is one quirk here, though.
readdir() returns NULL under two conditions: if an error occurs or once you have traversed all the files in the directory. To distinguish between these two cases, be sure to examine
errno after every
readdir() call. Remember that
readdir() doesn't change
errno unless an error has occurred. Therefore, reset
errno explicitly before calling this function.
 | |
| Figure 1. Typical Output: This is an example of the typical output of the program. |
After viewing the contents of directory you need to close it explicitly by calling closedir():
int closedir (DIR * pdir);
pdir is the result of a previous
opendir() call. Here is a complete program that lists the contents of the current directory:
#include <errno.h>
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
DIR *pdir;
struct dirent *pent;
pdir=opendir("."); //"." refers to the current dir
if (!pdir){
printf ("opendir() failure; terminating");
exit(1);
}
errno=0;
while ((pent=readdir(pdir))){
printf("%s", pent->d_name);
}
if (errno){
printf ("readdir() failure; terminating");
exit(1);
}
closedir(pdir);
}
Figure 1 shows a typical output from this program.