FAT | RFS | XFS | ZFS

readdir()

PROTOTYPE

#include <posix.h>

struct dirent *readdir(DIR *dirp);

DESCRIPTION

readdir() accesses the entry list of the directory referenced by dirp, a handle previously returned by opendir(). If the directory is empty or its current position is past its last entry, readdir() returns NULL. Otherwise, it returns a pointer to a structure containing information about the current entry and advances the current position to the next entry.

The dirent structure referenced by readdir()’s return value will be overwritten by another readdir() call for the same directory. It is not overwritten by a readdir() call on another directory. The structure is defined in “posix.h” and reproduced below:

struct dirent
{
  long d_ino;                /* volume-unique file ID */
  char d_name[FILENAME_MAX]; /* name of directory entry */
};

opendir() and rewinddir() both reset a directory’s current entry to its first entry. If directory entry is removed or added after these calls, the value returned by the next readdir() call is undefined.

If an error occurs or the current position is past the last entry, readdir() returns NULL. Otherwise, it updates the directory’s data access timestamp and returns a structure pointer. The initial “end of list” condition does not set errno. To differentiate between it and an error, clear errno before calling readdir() and test the value of errno if NULL is returned.

ERROR CODES

EBADF dirp is not the handle of an open directory.
ENOENT The current position is invalid (end of list was previously reported).

EXAMPLE

/*-------------------------------------------------------------*/
/* Print the name of every file in the directory.              */
/*-------------------------------------------------------------*/
while (entry = readdir(cur_dir))
  printf("%s\n", entry->d_name);