How to sort files in some directory by the names on Linux

JavaMobile picture JavaMobile · Feb 24, 2011 · Viewed 20.5k times · Source

I use opendir() and readdir() to display the file names in a directory. But they are disordered. How can I sort them? The language is C.

Answer

hipe picture hipe · Feb 24, 2011

Maybe you could use scandir() instead of opendir and readdir?

#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>

int
main(void)
{
   struct dirent **namelist;
   int n;

   n = scandir(".", &namelist, 0, alphasort);
   if (n < 0)
       perror("scandir");
   else {
       while (n--) {
       printf("%s\n", namelist[n]->d_name);
       free(namelist[n]);
       }
       free(namelist);
   }
}