在 CentOS(Linux) 下,readdir 本身不会排序,它返回的文件顺序是不确定的(依赖于文件系统的实现)。
如果你需要对 readdir 读取的结果进行排序,常见做法有下面几种:
readdir + scandir(推荐)scandir 本身支持排序函数:
#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:按版本号排序(CentOS 较新 glibc 支持)
readdir + qsort(手动排序)#include <dirent.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.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[1024];
int count = 0;
while ((entry = readdir(dir)) && count < 1024) {
names[count++] = strdup(entry->d_name);
}
closedir(dir);
qsort(names, count, sizeof(char *), compare);
for (int i = 0; i < count; i++) {
printf("%s\n", names[i]);
free(names[i]);
}
return 0;
}
如果你只是想在命令行里用:
ls -1 | sort
或:
for f in *; do echo "$f"; done | sort
stat() 获取信息后再排序| 方式 | 是否排序 | 说明 |
|---|---|---|
readdir |
❌ | 不排序 |
scandir + alphasort |
✅ | 推荐 |
readdir + qsort |
✅ | 灵活 |
shell sort |
✅ | 非程序 |
如果你能说明是 C / C++ / Shell / 内核模块,我可以给你更精确的示例。