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.
Asked
Active
Viewed 2.4k times
13

kumar
- 2,530
- 6
- 33
- 57

JavaMobile
- 409
- 4
- 6
- 18
-
@Christoffer Hammarström: Sorry, I forget to mention I have to use C – JavaMobile Feb 24 '11 at 10:07
-
You should add the `C` tag then. – Christoffer Hammarström Feb 24 '11 at 10:14
-
This is harder than it looks because Unix sorts files in idiomatic order, that is, p5A comes before p10A and p50A. Unless you rename files p05A, your alphabetic sort will not get the fine points of sort-by-name. – DragonLord Aug 19 '17 at 18:11
3 Answers
32
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);
}
}

hipe
- 802
- 6
- 8
-
In fact, I try to use it, but it has some errors. Could you give some examples or details? – JavaMobile Feb 24 '11 at 13:12
-
3You can find an example for how to use `scandir` (with alphabetic sorting) in the specification (see the examples section): http://pubs.opengroup.org/onlinepubs/9699919799/functions/scandir.html – R.. GitHub STOP HELPING ICE Feb 24 '11 at 15:10
8
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).

unwind
- 391,730
- 64
- 469
- 606
-
2`scandir` does this for you. The only bad part about it is that you can't specify the directory using a file descriptor; you have to pass the name. – R.. GitHub STOP HELPING ICE Feb 24 '11 at 15:14
0
You have to dynamically construct a data structure containing the filenames and make sure it is sorted.
You could build an array or linked list with the names, and then sort that, but my preference is to sort the values on insertion by inserting into a binary tree.

Christoffer Hammarström
- 27,242
- 4
- 49
- 58