Directory Entry (dirent)

Detailed Description

This interface accesses directory entries (both files and folders). Here is an example of how to use this interface.

#include <dirent.h>
#include <stdio.h>
void show_directory(){
DIR * dirp;
struct dirent entry;
struct dirent * result;
dirp = opendir("/path/to/dir");
if ( dirp == NULL ){
perror("failed to open directory");
return;
}
while( readdir_r(dirp, &entry, &result) == 0 ){
printf("Directory name (number): %s (%d)\n", entry.d_name, entry.d_ino);
}
if ( closedir(dirp) < 0 ){
perror("failed to close directory");
}
}

Data Structures

struct  dirent
 Directory Entry. More...
 

Functions

int closedir (DIR *dirp)
 
DIR * opendir (const char *dirname)
 
struct direntreaddir (DIR *dirp)
 
int readdir_r (DIR *dirp, struct dirent *entry, struct dirent **result)
 
void rewinddir (DIR *dirp)
 
void seekdir (DIR *dirp, long loc)
 
long telldir (DIR *dirp)
 

Function Documentation

◆ closedir()

int closedir ( DIR *  dirp)

Closes the directory stream specified by dirp.

Returns
Zero or -1 with errno (see Error Numbers) set to:
  • EINVAL: dirp does not refere to an open directory stream
Parameters
dirpA pointer to the open directory

◆ opendir()

DIR * opendir ( const char *  dirname)

Opens a directory.

Returns
a pointer to the directory or NULL with errno (see Error Numbers) set to:
  • ENOMEM: not enough memory
  • ENOENT: dirname was not found
  • EACCES: read access to dirname is not allowed
  • ENAMETOOLONG: dirname exceeds PATH_MAX or an element of dirname exceeds NAME_MAX

◆ readdir()

struct dirent * readdir ( DIR *  dirp)

Reads the next directory entry in the open directory.

Note
This function is not thread-safe nor re-entrant; use readdir_r() as a thread-safe, re-entrant alternative.
Returns
a pointer to a dirent or NULL with errno (see Error Numbers) set to:
  • EBADF: dirp is invalid
  • ENOENT: the current position of the directory stream is invalid
Parameters
dirpa pointer to the directory structure

◆ readdir_r()

int readdir_r ( DIR *  dirp,
struct dirent entry,
struct dirent **  result 
)

Reads the next directory entry in the open directory (reentrant version).

Returns
a pointer to a dirent or NULL with errno (see Error Numbers) set to:
  • EBADF: dirp is invalid
  • ENOENT: the current position of the directory stream is invalid
Parameters
dirpa pointer to the directory structure
entrya pointer to the destination memory
resultthis value is assigned to entry on success and NULL on failure

◆ rewinddir()

void rewinddir ( DIR *  dirp)

Rewinds dirp.

Parameters
dirpa pointer to the directory structure

◆ seekdir()

void seekdir ( DIR *  dirp,
long  loc 
)

Seeks to the specified location in the directory.

Parameters
dirpa pointer to the directory structure
locthe target location

◆ telldir()

long telldir ( DIR *  dirp)

Gets the current location in the directory.

Returns
The current directory location
Parameters
dirpa pointer to the directory structure