Use the glibc scandir function from <dirent.h> to list all the files in a directory using the C programming language. The scandir function allows for sorting, comparing and filtering the names of files in the directory. There are default options to list alphabetically through the alphasort() glibc standard function.

C code to List files in Directory

Below is a simple example, mainly taken from man scandir, with the execption of adding filtering logic. The filtering logic would typically be done on the name of the file which is found in the dirent.d_name structure member. If you don’t want a filter instead of passing in the function you can simply set the argument to NULL.

#define _DEFAULT_SOURCE
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/*
 The filter function allows us
 to not list files in the directory.

 Typically we analyze name->d_name
 and return 0 if you DO NOT want
 it in the returned list of files.

 Returning 1 will allow all files
 to be listed.
*/
int
filter(const struct dirent *name)
{
  return 1;
}

int
main(int argc, char *argv[])
{
  struct dirent **namelist;
  int n;

  /*
   List files in the current working directory.
   These are the files that are in the directory
   from which the process was run.
  */
  n = scandir(".", &namelist, filter, alphasort);
  if (n == -1) {
    perror("scandir");
    exit(EXIT_FAILURE);
  }

  while (n--) {
    printf("%s\n", namelist[n]->d_name);
    free(namelist[n]);
  }
  free(namelist);

  exit(EXIT_SUCCESS);
}

Notes on the example

There are a couple of details to note. Firstly, we #define _DEFAULT_SOURCE. This will allow us to “enable features from the 2008 edition of POSIX, as well as certain BSD and SVID features without a separate feature test macro to control them”. It’s worth reading more on this macro definition as it could have some implications.

Secondly, another function is defined called scandirat(). This function accepts one more argument which is a file descriptor of a directory to scan a directory from. Again, consult man scandir for more information.

Running the Example

If you want to try this example download cdirlist-1.0.tar.gz and run the following:

$ tar zxf cdirlist-1.0.tar.gz
$ cd cdirlist-1.0
$ ./configure
$ make
$ ./src/cdirlist