在 Linux 下使用 readdir() 读取目录时,readdir 本身不会排序,返回的顺序依赖于文件系统在目录项里的存储顺序(通常是无序的)。
如果你想“排序”,正确做法是在 readdir 之后自己排序。
下面按常见需求给你几种做法。
#include <dirent.h>
#include <stdio.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 <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_FILES 1024
int compare(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[MAX_FILES];
int count = 0;
while ((entry = readdir(dir)) && count < MAX_FILES) {
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((void *)names[i]);
}
return 0;
}
✅ 按 字典序(ASCII)排序
int compare(const void *a, const void *b) {
return atoi(*(const char **)a) - atoi(*(const char **)b);
}
或更严谨地用 strtol
#include <sys/stat.h>
struct FileInfo {
char name[256];
time_t mtime;
};
int compare(const void *a, const void *b) {
return ((struct FileInfo *)a)->mtime - ((struct FileInfo *)b)->mtime;
}
读取时:
struct stat st;
stat(entry->d_name, &st);
info[i].mtime = st.st_mtime;
strcpy(info[i].name, entry->d_name);
scandir(推荐)#include <dirent.h>
#include <stdio.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);
}
✅ 自动按文件名排序 ✅ 比 readdir + qsort 简单
ls -1 | sort
| 需求 | 推荐方式 |
|---|---|
| 简单文件名排序 | scandir + alphasort |
| 自定义排序 | readdir + qsort |
| 按时间/大小 | readdir + stat |
| 快速脚本 | `ls |
如果你告诉我:
我可以直接给你一份完整可编译代码。