getdents - Linux


Overview

getdents retrieves directory entries from a file descriptor. It’s commonly used to list files or directories in a specific path.

Syntax

getdents(fd, direntbuf, nbytes)

Options/Flags

  • direntbuf: Pointer to a buffer to receive the directory entries.
  • nbytes: Size of the buffer.
  • fd: File descriptor of the directory to be read.

Examples

Simple example

#include <dirent.h>

int main() {
  DIR *dir = opendir(".");
  struct dirent *ent;
  while ((ent = readdir(dir)) != NULL) {
    printf("%s\n", ent->d_name);
  }
  return 0;
}

Filtering by file type

#include <dirent.h>
#include <sys/stat.h>

int main() {
  DIR *dir = opendir(".");
  struct dirent *ent;
  struct stat st;
  while ((ent = readdir(dir)) != NULL) {
    lstat(ent->d_name, &st);
    if (S_ISDIR(st.st_mode)) {
      printf("%s (directory)\n", ent->d_name);
    }
  }
  return 0;
}

Common Issues

  • If nbytes is too small, getdents may return -1 and set errno to EINVAL.
  • If the file descriptor is invalid, getdents will return -1 and set errno to EBADF.
  • If there are too many entries to fit in the buffer, getdents may return -1 and set errno to EOVERFLOW.

Integration

getdents can be used in conjunction with other commands to perform various tasks. For example:

find / -type f | xargs -n 1 getdents

Related Commands