在 Ubuntu(Linux)下使用 readdir 读取目录时,readdir 本身是不会排序的,它返回的顺序依赖于底层文件系统(通常是目录项在磁盘上的存储顺序,看起来是“乱的”)。
如果你需要排序结果,常见做法有:
readdir 读取后再排序(最常用)scandir(推荐)scandir 可以直接排序,比 readdir 方便很多。
#include <dirent.h>
#include <stdio.h>
int main() {
struct dirent **namelist;
int n = scandir(".", &namelist, NULL, alphasort);
if (n < 0) {
perror("scandir");
return 1;
}
for (int i = 0; i < n; i++) {
printf("%s\n", namelist[i]->d_name);
free(namelist[i]);
}
free(namelist);
return 0;
}
✅ alphasort:按字母排序
✅ versionsort:按版本号排序(Ubuntu 支持)
readdir + 手动排序如果你必须用 readdir:
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int compare(const void *a, const void *b) {
return strcmp(*(const char **)a, *(const char **)b);
}
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*), compare);
for (int i = 0; i < count; i++) {
printf("%s\n", names[i]);
free(names[i]);
}
free(names);
return 0;
}
sortls | sort
system("ls | sort");
(不推荐,除非简单脚本)
| 方法 | 是否排序 | 推荐度 |
|---|---|---|
readdir |
❌ 不排序 | ⭐⭐ |
scandir + alphasort |
✅ 字母序 | ⭐⭐⭐⭐⭐ |
readdir + qsort |
✅ 自定义 | ⭐⭐⭐⭐ |
system("ls") |
✅ | ⭐ |
如果你有特定排序需求(比如:
. 和 ..可以告诉我,我给你写对应代码。