在 CentOS(本质上是 Linux 下使用 glibc 的 readdir / readdir_r)中,readdir() 本身返回的目录项顺序是不确定的(通常是文件系统内部的顺序,不一定是字母序)。
如果你需要“排序”,正确做法是用 readdir 读取所有条目,然后自己排序。
下面按常见需求给你几种做法。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
int compare(const void *a, const void *b) {
return strcmp(*(const char **)a, *(const char **)b);
}
int main(int argc, char *argv[]) {
const char *path = ".";
DIR *dir = opendir(path);
if (!dir) {
perror("opendir");
return 1;
}
struct dirent *entry;
char **names = NULL;
int count = 0, cap = 0;
while ((entry = readdir(dir)) != NULL) {
if (count >= cap) {
cap = cap ? cap * 2 : 16;
names = realloc(names, cap * sizeof(char *));
}
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]);
}
free(names);
return 0;
}
✅ 优点
用 stat() 获取时间:
struct stat st;
stat(entry->d_name, &st);
st.st_mtime // 修改时间
然后按 st_mtime 排序即可。
如果你只是想看排序结果:
ls -1 # 按名排序
ls -lt # 按修改时间
ls -lS # 按大小
❌ readdir() 返回顺序 ≠ 排序
❌ 不同文件系统(ext4 / xfs)顺序可能不同
❌ 不要依赖 readdir 的顺序写逻辑
| 需求 | 做法 |
|---|---|
| 文件名排序 | readdir + qsort |
| 时间排序 | readdir + stat |
| 只是查看 | ls |
| 高性能 | 读取后一次性排序 |
如果你是 C / C++ / Python / 特定场景(如递归目录),可以告诉我,我给你对应版本。