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.
How to sort files in some directory by the names on Linux
24.5k Views Asked by JavaMobile At
3
There are 3 best solutions below
2

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);
}
}
The idiomatic way to sort something in C is to use the
qsort()
function. For this to work, it's best if you can arrange to have all the file names collected into an array of pointers, and then you sort the array.This is not too hard, but it does require either a bit of dynamic-array management, or that you introduce static limits on things (maximum length of filenames, maximum number of files).