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

时光毁灭记忆、已成空白 提交于 2019-12-12 07:07:01

问题


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.


回答1:


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




回答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);
   }
}



回答3:


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.



来源:https://stackoverflow.com/questions/5102863/how-to-sort-files-in-some-directory-by-the-names-on-linux

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!