Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 423
JavaMobile Avatar asked Feb 24 '11 09:02

JavaMobile


People also ask

How do I sort files by name in Linux?

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, .

How do I sort files by file names?

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.

How do I list files alphabetically in Linux?

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.


1 Answers

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);
   }
}
like image 136
hipe Avatar answered Oct 23 '22 14:10

hipe