Listing Directory Files

This week, I will show how to programmatically access a directory's

files.

The POSIX standard defines abstract functions and data types for

accessing a directory's files in a portable manner, regardless of the

actual file system used. These functions and data types are declared in

the header file

. The two main data structures are DIR and dirent. You use a pointer to DIR to iterate through a directory's files. The second data structure, dirent, represents a directory file. Most of the fields in the structure dirent are not portable; they depend on the actual file system you're using. However, the field d_name, which stores the current directory file's name, is portable and that's the only thing we care about. Before you can iterate the a directory's files, you have to open it explicitly using the opendir() function: #include DIR *pdir=opendir (const char *path); Similarly, you use the closedir() function to close a directory once you're done: int closedir(DIR * pdir); Remember, you can open directories only for reading. Therefore, opendir () takes a single parameter, namely the directory's pathname, which must be an existing directory's name (you can't create a new directory using opendir(); instead use mkdir()). Once you've opened a directory successfully, you access the entries therein sequentially until you've reached the directory's end. The function readdir() returns a dirent pointer associated with the next directory file. Here is the prototype of this function: dirent* pfile readdir(DIR * pdir); readdir() returns a NULL pointer when the directory contains no more entries, or when an error has occurred. If you must distinguish between these two conditions, then you should reset errno before calling readdir () and check its value afterwards. The following program opens the current directory, retrieves its files in a loop, and writes their names to the standard output. You can easily turn it into a generic directory-listing program by passing the directory pathname as a command line argument. #include #include #include int main() { DIR *pdir; struct dirent *pfile; if (!(pdir=opendir ("."); /*open current directory*/ { perror("opendir"); return -1; } errno=0; /*reset before calling readdir*/ while(pfile=readdir(pdir)) { printf("%s\n",pfile->d_name); } if (errno==0) closedir(pdir); return 0; } To re-read the current directory from the beginning, use the rewinddir () function. After calling rewinddir(), readdir() will return the first file in the directory: int rewinddir(DIR *pdir);
What’s wrong? The new clean desk test
Join the discussion
Be the first to comment on this article. Our Commenting Policies