在 CentOS(Linux) 下,readdir 本身不会排序,它返回目录项的顺序是文件系统决定的(通常是 hash 或 inode 顺序)。
如果你需要排序,必须在 应用层自己排序。
下面分几种常见情况说明。
readdir() 读取的是 struct dirent,顺序由文件系统决定:
✅ POSIX 不保证 readdir 的顺序
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
int main() {
DIR *dir = opendir(".");
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
closedir(dir);
return 0;
}
⚠️ 输出是无序的
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
int cmp(const void *a, const void *b) {
return strcmp(*(const char **)a, *(const char **)b);
}
int main() {
DIR *dir = opendir(".");
struct dirent *entry;
const char *names[1024];
int count = 0;
while ((entry = readdir(dir)) != NULL && count < 1024) {
names[count++] = strdup(entry->d_name);
}
closedir(dir);
qsort(names, count, sizeof(char *), cmp);
for (int i = 0; i < count; i++) {
printf("%s\n", names[i]);
free((char *)names[i]);
}
return 0;
}
✅ 按字母排序
需要 stat():
#include <sys/stat.h>
#include <sys/types.h>
#include <time.h>
然后比较:
struct stat st;
stat(name, &st);
st.st_mtime; // 修改时间
ls -1 | sort
ls -lt
ls -lS
import os
files = os.listdir('.')
files.sort()
print(files)
| 场景 | 是否自动排序 |
|---|---|
| readdir() | ❌ 不排序 |
| ls | ✅ 默认排序 |
| 自己写程序 | ✅ 需手动排序 |
| 按时间排序 | ✅ 需 stat() |
如果你能说明:
. 和 ..我可以给你更精确的示例。