Opening a Directory for Searching

It is often necessary to search a directory to determine what entries the directory contains. For example, a backup utility would need to visit all files and subdirectories as it is backing them up. A family of functions, starting with opendir(3), is provided for that purpose:

#include <sys/types.h>
#include <dirent.h>

DIR *opendir(const char *pathname);

int dirfd(DIR *dirp);

In the synopsis, note the return value provided by the function opendir(3). This is similar to the fopen(3) call in the way that it returns a pointer to a structure. Here, the opendir(3) function returns a pointer to the data type DIR. The argument pathname is the name of the directory to be opened for searching.

The function opendir(3) returns a pointer when successful and a null pointer when it fails. The error code is placed in errno when the function call fails.

The pointer to DIR cannot be used in other functions such as fchdir(2), for example, so a function dirfd(3) is provided (this may be implemented as a macro). The following example shows how opendir(3) and dirfd(3) might be used together:

DIR *dirp;             /* Ptr to open directory */
int fd;                /* fd of open directory */

dirp = opendir("/etc");
if ( !dirp ) {
    /* report error */
}  else {
    …   /* Do some stuff here */
    fd = dirfd(dirp);  /* Get fd of open directory */
    if ( fchdir(fd) == -1 ) {
        /* Report failed fchdir(2) */
    }
}
					

Note

The dirfd(3) function is not available on many UNIX platforms. FreeBSD and SGI IRIX 6.5 support this function.

IRIX 6.5 supports the dirfd(3) function if you include the 4.3BSD file <sys/dir.h> instead of the System V include file <dirent.h>.


The example shows how opendir(3) opens the directory /etc. Later, with the help of the function dirfd(3), the file descriptor is fetched out of the structure pointed to by dirp and assigned to variable fd. Once fd is established, the function fchdir(2) can be called to make the open directory the current directory.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.217.4.206