如何在Linux上按名称对某个目录中的文件进行排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5102863/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 02:59:50  来源:igfitidea点击:

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

clinuxfilesortingscandir

提问by JavaMobile

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.

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

采纳答案by unwind

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.

在 C 中对某些内容进行排序的惯用方法是使用该qsort()函数。为此,最好可以安排将所有文件名收集到一个指针数组中,然后对数组进行排序。

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

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

回答by hipe

Maybe you could use scandir() instead of opendir and readdir?

也许您可以使用 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);
   }
}

回答by Christoffer Hammarstr?m

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.

您可以使用名称构建一个数组或链表,然后对其进行排序,但我的偏好是通过插入二叉树来对插入时的值进行排序。