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.
If you add the -X option, ls will sort files by name within each extension category. For example, it will list files without extensions first (in alphanumeric order) followed by files with extensions like . 1, . bz2, .
To sort files in a different order, click the view options button in the toolbar and choose By Name, By Size, By Type, By Modification Date, or By Access Date. As an example, if you select By Name, the files will be sorted by their names, in alphabetical order.
As we already mentioned, by default, the ls command is listing the files in alphabetical order. The --sort option allows you to sort the output by extension, size, time and version: --sort=extension (or -X ) - sort alphabetically by extension. --sort=size (or -S ) - sort by file size.
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With