directory

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

}

Details

int closedir(

DIR * dirp
)

Closes the directory stream specified by dirp.

Returns

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

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

DIR * opendir(

const char * dirname
)

Opens a directory.

Returns

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

struct dirent * readdir(

DIR * dirp
)

Reads the next directory entry in the open directory. 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 Errno) set to:

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

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 Errno) set to:

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

void rewinddir(

DIR * dirp
)

Rewinds dirp.


void seekdir(

DIR * dirp,
long loc
)

Seeks to the specified location in the directory.


long telldir(

DIR * dirp
)

Gets the current location in the directory.

Returns

The current directory location


struct::dirent

This defines the data structure for a directory entry.

ino_t d_ino

char d_name

struct::DIR

const void * fs

void * handle

long loc

unsigned int checksum

X

Thanks for Coming!

Subscribe to news and updates