readdir, readdir_r - read a directory
#include <dirent.h>
struct dirent *readdir(DIR *dirp);[TSF]int readdir_r(DIR *restrictdirp, struct dirent *restrictentry,
struct dirent **restrictresult);
The typeDIR, which is defined in the<dirent.h> header, representsadirectory stream, which is an ordered sequence of all the directory entries in a particular directory. Directory entriesrepresent files; files may be removed from a directory or added to a directory asynchronously to the operation ofreaddir().
Thereaddir() function shall return a pointer to a structure representing the directory entry at the current position inthe directory stream specified by the argumentdirp, and position the directory stream at the next entry. It shall return anull pointer upon reaching the end of the directory stream. The structuredirent defined in the<dirent.h> header describes a directory entry.
Thereaddir() function shall not return directory entries containing empty names. If entries for dot or dot-dot exist,one entry shall be returned for dot and one entry shall be returned for dot-dot; otherwise, they shall not be returned.
The pointer returned byreaddir() points to data which may be overwritten by another call toreaddir() on the samedirectory stream. This data is not overwritten by another call toreaddir() on a different directory stream.
If a file is removed from or added to the directory after the most recent call toopendir() orrewinddir(), whether asubsequent call toreaddir() returns an entry for that file is unspecified.
Thereaddir() function may buffer several directory entries per actual read operation;readdir() shall mark forupdate thest_atime field of the directory each time the directory is actually read.
After a call tofork(), either the parent or child (but not both) may continueprocessing the directory stream usingreaddir(),rewinddir(),[XSI]
orseekdir().
If both theparent and child processes use these functions, the result is undefined.
If the entry names a symbolic link, the value of thed_ino member is unspecified.
Thereaddir() function need not be reentrant. A function that is not required to be reentrant is not required to bethread-safe.
[TSF]
Thereaddir_r() function shall initialize thedirent structure referenced byentry to represent the directoryentry at the current position in the directory stream referred to bydirp, store a pointer to this structure at the locationreferenced byresult, and position the directory stream at the next entry.
The storage pointed to byentry shall be large enough for adirent with an array ofchard_namemembers containing at least {NAME_MAX}+1 elements.
Upon successful return, the pointer returned at *result shall have the same value as the argumententry. Uponreaching the end of the directory stream, this pointer shall have the value NULL.
Thereaddir_r() function shall not return directory entries containing empty names.
If a file is removed from or added to the directory after the most recent call toopendir() orrewinddir(), whether asubsequent call toreaddir_r() returns an entry for that file is unspecified.
Thereaddir_r() function may buffer several directory entries per actual read operation; thereaddir_r() functionshall mark for update thest_atime field of the directory each time the directory is actually read.
Applications wishing to check for error situations should seterrno to 0 before callingreaddir(). Iferrnois set to non-zero on return, an error occurred.
Upon successful completion,readdir() shall return a pointer to an object of typestruct dirent. When an error isencountered, a null pointer shall be returned anderrno shall be set to indicate the error. When the end of the directory isencountered, a null pointer shall be returned anderrno is not changed.
[TSF]
If successful, thereaddir_r() function shall return zero; otherwise, an error number shall be returned to indicate theerror.
Thereaddir() function shall fail if:
- [EOVERFLOW]
- One of the values in the structure to be returned cannot be represented correctly.
Thereaddir() function may fail if:
- [EBADF]
- Thedirp argument does not refer to an open directory stream.
- [ENOENT]
- The current position of the directory stream is invalid.
Thereaddir_r() function may fail if:
- [EBADF]
- Thedirp argument does not refer to an open directory stream.
The following sample program searches the current directory for each of the arguments supplied on the command line.
#include <dirent.h>#include <errno.h>#include <stdio.h>#include <string.h>
static void lookup(const char *arg){ DIR *dirp; struct dirent *dp;
if ((dirp = opendir(".")) == NULL) { perror("couldn't open '.'"); return; }
do { errno = 0; if ((dp = readdir(dirp)) != NULL) { if (strcmp(dp->d_name, arg) != 0) continue;
(void) printf("found %s\n", arg); (void) closedir(dirp); return;
} } while (dp != NULL);
if (errno != 0) perror("error reading directory"); else (void) printf("failed to find %s\n", arg); (void) closedir(dirp); return;}
int main(int argc, char *argv[]){ int i; for (i = 1; i < argc; i++) lookup(argv[i]); return (0);}
Thereaddir() function should be used in conjunction withopendir(),closedir(), andrewinddir() toexamine the contents of the directory.
Thereaddir_r() function is thread-safe and shall return values in a user-supplied buffer instead of possibly using astatic data area that may be overwritten by each call.
The returned value ofreaddir() merelyrepresents a directory entry. No equivalence should be inferred.
Historical implementations ofreaddir() obtain multiple directory entries on a single read operation, which permitssubsequentreaddir() operations to operate from the buffered information. Any wording that required each successfulreaddir() operation to mark the directoryst_atime field for update would disallow such historicalperformance-oriented implementations.
Sincereaddir() returns NULL when it detects an error and when the end of the directory is encountered, an applicationthat needs to tell the difference must seterrno to zero before the call and check it if NULL is returned. Since thefunction must not changeerrno in the second case and must set it to a non-zero value in the first case, a zeroerrnoafter a call returning NULL indicates end-of-directory; otherwise, an error.
Routines to deal with this problem more directly were proposed:
int derror (dirp)DIR *dirp;
void clearderr (dirp)DIR *dirp;The first would indicate whether an error had occurred, and the second would clear the error indication. The simpler methodinvolvingerrno was adopted instead by requiring thatreaddir() not changeerrno when end-of-directory isencountered.
An error or signal indicating that a directory has changed while open was considered but rejected.
The thread-safe version of the directory reading function returns values in a user-supplied buffer instead of possibly using astatic data area that may be overwritten by each call. Either the {NAME_MAX} compile-time constant or the correspondingpathconf() option can be used to determine the maximum sizes of returned pathnames.
None.
closedir(),lstat(),opendir(),rewinddir(),symlink(), the Base Definitions volume of IEEE Std 1003.1-2001,<dirent.h>,<sys/types.h>
First released in Issue 2.
Large File Summit extensions are added.
Thereaddir_r() function is included for alignment with the POSIX Threads Extension.
A note indicating that thereaddir() function need not be reentrant is added to the DESCRIPTION.
Thereaddir_r() function is marked as part of the Thread-Safe Functions option.
The Open Group Corrigendum U026/7 is applied, correcting the prototype forreaddir_r().
The Open Group Corrigendum U026/8 is applied, clarifying the wording of the successful return for thereaddir_r()function.
The following new requirements on POSIX implementations derive from alignment with the Single UNIX Specification:
The requirement to include<sys/types.h> has been removed. Although<sys/types.h> was required for conforming implementations of previous POSIXspecifications, it was not required for UNIX applications.
A statement is added to the DESCRIPTION indicating the disposition of certain fields instruct dirent when an entryrefers to a symbolic link.
The [EOVERFLOW] mandatory error condition is added. This change is to support large files.
The [ENOENT] optional error condition is added.
The APPLICATION USAGE section is updated to include a note on the thread-safe function and its avoidance of possibly using astatic data area.
Therestrict keyword is added to thereaddir_r() prototype for alignment with the ISO/IEC 9899:1999standard.
IEEE Std 1003.1-2001/Cor 1-2002, item XSH/TC1/D6/50 is applied, replacing the EXAMPLES section with a new example.