How do you get a directory listing in C?

The following POSIX program will print the names of the files in the current directory:

#define _XOPEN_SOURCE 700
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>

int main (void)
{
  DIR *dp;
  struct dirent *ep;     
  dp = opendir ("./");
  if (dp != NULL)
  {
    while ((ep = readdir (dp)) != NULL)
      puts (ep->d_name);
          
    (void) closedir (dp);
    return 0;
  }
  else
  {
    perror ("Couldn't open the directory");
    return -1;
  }
}

Credit: http://www.gnu.org/software/libtool/manual/libc/Simple-Directory-Lister.html

Tested in Ubuntu 16.04.

Leave a Comment