![]() |
![]() |
![]() |
Open a directory
#include <dirent.h> DIR* opendir( const char* dirname );
libc
The opendir() function is used with readdir() and closedir() to get the list of file names contained in the directory specified by dirname. The dirname can be relative to the current working directory or an absolute path.
The <dirent.h> header file contains definitions for the dirent structure. <!- removing this bit because the definition in the header file provides no useful information (it's just a hidden structure): and the DIR type. -->
More than one directory can be read at the same time using the opendir(), readdir(), rewinddir() and closedir() functions.
![]() |
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(). |
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).
To 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; }
Safety: | |
---|---|
Cancellation point | Yes |
Interrupt handler | No |
Signal handler | No |
Thread | Yes |
closedir(), errno, readdir(), readdir_r(), rewinddir()
![]() |
![]() |
![]() |