#include <sys/types.h> #include <sys/dir.h> /* POSIX applications #include <dirent.h> */ DIR *opendir(const char *dirname); struct direct *readdir(DIR *dirp); /* Returns struct dirent * for POSIX applications. */ void rewinddir(DIR *dirp); int closedir(DIR *dirp);
long telldir(DIR *dirp); int seekdir(DIR *dirp, long loc);
The readdir function returns a pointer to a direct structure ( dirent for POSIX applications) representing the directory entry at the current position in the directory stream referred to by dirp, and positions the directory stream at the next entry. It returns a NULL pointer upon reaching the end of the directory stream.
The direct/dirent structure includes the following member:
The rewinddir function resets the position of the directory stream referred to by dirp to the beginning of the directory. It does not return a value.
The closedir function closes the directory stream referred to by dirp and frees the structure.
The following sample code searches the current working directory for directory entry ``name'':
len = strlen(name);
dirp = opendir(".");
for (dp = readdir(dirp); dp != NULL; dp = readdir(dirp)) {
if (dp->d_namlen == len && !strcmp(dp->d_name, name)) {
closedir(dirp);
return FOUND;
}
}
closedir(dirp);
return NOT_FOUND;
Telldir returns the current location associated with the named directory stream.
Seekdir sets the position of the next readdir operation on the directory stream. The new position reverts to the one associated with the directory stream when the telldir operation was performed. Values returned by telldir are good only for the lifetime of the DIR pointer from which they are derived. If the directory is closed and then reopened, the telldir value may be invalidated due to undetected directory compaction. It is safe to use a previous telldir value immediately after a call to opendir and before any calls to readdir.
Upon successful completion, readdir returns a pointer to a direct/dirent structure. When an error occurs, a NULL pointer is returned and errno is set to indicate the error. When the end of the directory stream is reached, a NULL pointer is returned and errno is left unchanged.
Upon successful completion, closedir returns zero. Otherwise, -1 is returned and errno is set to indicate the error.
If any of the following conditions occurs, the readdir function returns a NULL pointer and sets errno to the corresponding value:
If any of the following conditions occurs, the closedir function returns -1 and sets errno to the corresponding value: