在 Linux 下使用 readdir() 读取目录时,readdir() 本身不会保证顺序(通常是文件系统内部的顺序,可能是乱的)。如果你需要对结果排序,常见做法有几种:
readdir() + 手动排序(最常用)opendir() / readdir() 读取所有条目struct dirent* 或文件名字符串)qsort() 排序#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() {
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;
}
#include <strings.h>
int compare(const void *a, const void *b) {
return strcasecmp(*(const char **)a, *(const char **)b);
}
#include <sys/stat.h>
int compare(const void *a, const void *b) {
struct stat sa, sb;
stat(*(const char **)a, &sa);
stat(*(const char **)b, &sb);
return sa.st_mtime - sb.st_mtime;
}
return sa.st_size - sb.st_size;
scandir()(更简单)scandir() 内部已经帮你排序:
#include <stdio.h>
#include <dirent.h>
int main() {
struct dirent **namelist;
int n = scandir(".", &namelist, NULL, alphasort);
for (int i = 0; i < n; i++) {
printf("%s\n", namelist[i]->d_name);
free(namelist[i]);
}
free(namelist);
return 0;
}
✅ alphasort:按字母排序
✅ versionsort:按版本号排序(glibc)
如果你是脚本或命令行:
ls -1 | sort
ls -lt # 按时间
ls -lS # 按大小
| 方式 | 是否排序 | 推荐场景 |
|---|---|---|
readdir() |
❌ | 需要完全控制 |
readdir() + qsort() |
✅ | 灵活排序 |
scandir() |
✅ | 最简单 |
如果你告诉我:
我可以给你更精确的代码。