WEBINAR:

On-Demand

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:

Advertiser Disclosure:
Some of the products that appear on this site are from companies from which QuinStreet receives compensation. This compensation may impact how and where products appear on this site including, for example, the order in which they appear. QuinStreet does not include all companies or all types of products available in the marketplace.

Thanks for your registration, follow us on our social networks to keep up-to-date