directory
Purpose
Performs operations on directories.
Library
Berkeley Library (libbsd.a)
Syntax
#include <bsd/sys/types.h>
#include <bsd/sys/dir.h>
DIR *opendir (dirname) void seekdir (dirp, loc)
char *dirname; DIR *dirp;
long loc;
struct direct *readdir (dirp)
DIR *dirp; rewinddir (dirp)
DIR *dirp;
long telldir (dirp)
DIR *dirp; void closedir (dirp)
DIR *dirp;
Description
The opendir subroutine opens the directory designated by
the dirname parameter and associates a directory stream
with it.
Note: An open directory must always be closed with the
closedir subroutine to ensure that the next attempt to
open that directory is successful.
The subroutine also returns a pointer to identify the
directory stream in subsequent operations. The pointer
NULL is returned when dirname cannot be accessed, or when
not enough memory is available to hold the whole stream.
The readdir subroutine returns a pointer to the next
directory entry. When it reaches the end of the direc-
tory, or when it detects an invalid seekdir operation,
readdir returns NULL.
The telldir subroutine returns the current location asso-
ciated with the specified directory stream.
Values returned by telldir are good only for the lifetime
of the DIR pointer from which they are derived. If a
directory is closed and reopened, the value telldir
returned may be invalidated. Therefore, you should use a
previous telldir value immediately after an opendir and
before any readdir subroutine.
The seekdir subroutine sets the position of the next
readdir operation on the directory stream. The new posi-
tion reverts to the one associated with the directory
stream by the telldir subroutine.
Note: The seekdir and telldir subroutines may not func-
tion correctly on file systems that do not have an
AIX-like structure.
The rewinddir subroutine resets the position of the spec-
ified directory stream to the beginning of the directory.
The closedir subroutine closes a directory stream and
frees the structure associated with the dirp parameter.
Examples
The following is a code sample that searches a directory
for 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;
Related Information
In this book: "close," "lseek," "open," "read, readx,"
"scandir," and "dir."