我使用opendir()
和readdir()
来显示目录中的文件名。但它们是无序的。如何排序它们?这是C语言。
也许你可以使用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);
}
}
scandir
(按字母顺序排序)的示例(请参见示例部分):http://pubs.opengroup.org/onlinepubs/9699919799/functions/scandir.html - R.. GitHub STOP HELPING ICE在C语言中,按惯例排序的方法是使用qsort()
函数。为了让它起作用,最好将所有文件名收集到指针数组中,然后对数组进行排序。
这并不太难,但需要一些动态数组管理,或者引入静态限制(文件名的最大长度、文件的最大数量)。
scandir
可以帮你完成这个任务。唯一的缺点是你不能使用文件描述符指定目录,你必须传递目录名称。 - R.. GitHub STOP HELPING ICE你需要动态构建一个数据结构,其中包含文件名,并确保它已排序。
你可以使用数组或链表来构建名称,然后对其进行排序,但我更喜欢通过将值插入二叉树来在插入时进行排序。
C
标签。 - Christoffer Hammarström