在 Linux 下使用 readdir() 读取目录时,readdir 本身不会排序,返回顺序是文件系统内部的顺序(通常是目录项在磁盘上的顺序)。如果你需要对结果排序,需要在用户态自己处理。
下面按常见需求说明做法。
#include <dirent.h>
DIR *dir = opendir(".");
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
closedir(dir);
结果顺序:不保证排序
先把所有文件名存起来,再用 qsort() 排序。
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.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;
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*), cmp);
for (int i = 0; i < count; i++) {
printf("%s\n", names[i]);
free(names[i]);
}
free(names);
}
需要 stat() 获取时间。
#include <sys/stat.h>
#include <time.h>
struct FileInfo {
char name[256];
time_t mtime;
};
int cmp_time(const void *a, const void *b) {
return ((struct FileInfo*)a)->mtime - ((struct FileInfo*)b)->mtime;
}
步骤:
readdir()stat(entry->d_name, &st)st.st_mtimeqsort()st.st_size
. 和 ..if (strcmp(entry->d_name, ".") == 0 ||
strcmp(entry->d_name, "..") == 0)
continue;
return strcasecmp(a, b);
scandir()(强烈推荐)#include <dirent.h>
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);
优点:
alphasort)| 方式 | 是否排序 | 说明 |
|---|---|---|
readdir |
❌ | 需手动排序 |
scandir |
✅ | 推荐 |
readdir + qsort |
✅ | 灵活 |
如果你有特定排序规则(中文、版本号、目录优先等),可以告诉我,我可以给针对性代码。