如何通过Linux上的名称对某些目录中的文件进行排序

Jav*_*ile 11 c linux sorting file scandir

我使用opendir()readdir()在目录中显示文件名.但他们是无序的.我怎么能对它们进行排序?语言是C.

hip*_*ipe 27

也许你可以使用scandir()而不是opendir和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);
   }
}
Run Code Online (Sandbox Code Playgroud)

  • 您可以在规范中找到如何使用`scandir`(带字母排序)的示例(请参阅示例部分):http://pubs.opengroup.org/onlinepubs/9699919799/functions/scandir.html (3认同)

unw*_*ind 7

在C中对事物进行排序的惯用方法是使用该qsort()函数.为了使其工作,最好是安排将所有文件名收集到一个指针数组中,然后对数组进行排序.

这不是太难,但它确实需要一些动态数组管理,或者你需要对事物引入静态限制(文件名的最大长度,文件的最大数量).

  • `scandir`为你做这件事.关于它的唯一不好的部分是你不能使用文件描述符指定目录; 你必须传递这个名字. (2认同)