在 Ubuntu(Linux)下,使用 readdir() 读取目录时,默认是无序的(通常是文件系统返回的顺序)。如果你要对目录项排序,常见做法有下面几种。
readdir() + 手动排序(C 语言)readdir() 本身不排序,需要你把结果存起来再排序。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
int main() {
DIR *dir = opendir(".");
struct dirent *entry;
char **names = NULL;
int count = 0;
while ((entry = readdir(dir)) != NULL) {
names = realloc(names, sizeof(char*) * (count + 1));
names[count] = strdup(entry->d_name);
count++;
}
closedir(dir);
// 排序
qsort(names, count, sizeof(char*),
(int (*)(const void*, const void*)) strcmp);
for (int i = 0; i < count; i++) {
printf("%s\n", names[i]);
free(names[i]);
}
free(names);
return 0;
}
✅ 特点
scandir()(推荐,自动排序)scandir() 内部会调用 readdir(),并自动排序。
#include <stdio.h>
#include <dirent.h>
int main() {
struct dirent **namelist;
int n = scandir(".", &namelist, NULL, alphasort);
if (n < 0) return 1;
for (int i = 0; i < n; i++) {
printf("%s\n", namelist[i]->d_name);
free(namelist[i]);
}
free(namelist);
return 0;
}
✅ 优点
alphasort)可选排序函数:
alphasort:字典序versionsort:版本号排序(如 file2 < file10)如果你只是想在终端里排序:
ls -1 | sort
ls -1 -t # 按时间
ls -1 -S # 按大小
| 排序方式 | 方法 |
|---|---|
| 文件名 | alphasort |
| 修改时间 | 读 stat() 再排序 |
| 文件大小 | 读 stat() 再排序 |
| 自然排序 | versionsort |
scandir()readdir() + qsort()如果你是 C / C++ / Python / Shell 哪种场景,我可以给你更具体的示例。