Skip to main content

Directory Entry (dirent)

More...

Classes#

Name
structdirent
Directory Entry.

Functions#

Name
intclosedir(DIR * dirp)
DIR *opendir(const char * dirname)
struct dirent *readdir(DIR * dirp)
intreaddir_r(DIR dirp, struct dirent entry, struct dirent ** result)
voidrewinddir(DIR * dirp)
voidseekdir(DIR * dirp, long loc)
longtelldir(DIR * dirp)

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");     }
}

Functions Documentation#

closedir#

int closedir(    DIR * dirp)

Return: Zero or -1 with errno (see Errno) set to:

  • EINVAL: dirp does not refere to an open directory stream

Closes the directory stream specified by dirp.

opendir#

DIR * opendir(    const char * dirname)

Return: a pointer to the directory or NULL with errno (see Errno) 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

Opens a directory.

readdir#

struct dirent * readdir(    DIR * dirp)

Return: a pointer to a dirent or NULL with errno (see Errno) set to:

  • EBADF: dirp is invalid
  • ENOENT: the current position of the directory stream is invalid

Note: This function is not thread-safe nor re-entrant; use readdir_r() as a thread-safe, re-entrant alternative.

Reads the next directory entry in the open directory.

readdir_r#

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

Return: a pointer to a dirent or NULL with errno (see Errno) set to:

  • EBADF: dirp is invalid
  • ENOENT: the current position of the directory stream is invalid

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

rewinddir#

void rewinddir(    DIR * dirp)

Rewinds dirp.

seekdir#

void seekdir(    DIR * dirp,    long loc)

Seeks to the specified location in the directory.

telldir#

long telldir(    DIR * dirp)

Return: The current directory location

Gets the current location in the directory.


Updated on 18 September 2021 at 21:44:10 MDT