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)
在C中对事物进行排序的惯用方法是使用该qsort()函数.为了使其工作,最好是安排将所有文件名收集到一个指针数组中,然后对数组进行排序.
这不是太难,但它确实需要一些动态数组管理,或者你需要对事物引入静态限制(文件名的最大长度,文件的最大数量).