opendir()

Open a directory

Synopsis:

#include <dirent.h>

DIR * opendir( const char * dirname );

Arguments:

dirname
The path of the directory to be opened. It can be relative to the current working directory, or an absolute path.

Library:

libc

Use the -l c option to qcc to link against this library. This library is usually included automatically.

Description:

The opendir() function is used with readdir() and closedir() to get the list of file names contained in the directory specified by dirname.

You can read more than one directory at the same time using the opendir(), readdir(), rewinddir() and closedir() functions.


Note: The result of using a directory stream after one of the exec*() or spawn*() functions is undefined. After a call to the fork() function, either the parent or the child (but not both) can continue processing the directory stream using readdir() and rewinddir(). If both the parent and child processes use these functions, the result is undefined. Either process can use closedir().

Returns:

A pointer to a DIR structure required for subsequent calls to readdir() to retrieve the file names in dirname, or NULL if dirname isn't a valid path (errno is set).

Errors:

EACCES
Search permission is denied for a component of dirname, or read permission is denied for dirname.
ELOOP
Too many levels of symbolic links or prefixes.
ENAMETOOLONG
The length of dirname exceeds PATH_MAX, or a pathname component is longer than NAME_MAX.
ENOENT
The named directory doesn't exist.
ENOSYS
The opendir() function isn't implemented for the filesystem specified in dirname.
ENOTDIR
A component of dirname isn't a directory.

Examples:

Get a list of files contained in the directory /home/fred:

#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>

int main( void )
{
    DIR* dirp;
    struct dirent* direntp;

    dirp = opendir( "/home/fred" );
    if( dirp == NULL ) {
        perror( "can't open /home/fred" );
    } else {
        for(;;) {
            direntp = readdir( dirp );
            if( direntp == NULL ) break;

            printf( "%s\n", direntp->d_name );
        }
        
        closedir( dirp );
    }
    
    return EXIT_SUCCESS;
}

Classification:

POSIX 1003.1

Safety:
Cancellation point Yes
Interrupt handler No
Signal handler No
Thread Yes

See also:

closedir(), dirent, errno, readdir(), readdir_r(), rewinddir(), seekdir(), telldir()