在 Debian(或者说 Linux 下 C/C++ 编程)里,readdir() 本身不会排序,返回的是目录项在文件系统里的顺序(通常是哈希或创建顺序,不确定)。
如果你需要“排序”,要在拿到结果后再自己排序。
下面按常见需求给你几种做法。
#include <dirent.h>
DIR *dir = opendir(".");
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
closedir(dir);
⚠️ 顺序不可控,不能依赖
scandir(最简单 ✅ 推荐)#include <dirent.h>
#include <stdio.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:字典序排序. 和 ..(如果不想过滤可自定义 filter)#include <dirent.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 *e;
char *names[1024];
int n = 0;
while ((e = readdir(dir)))
names[n++] = strdup(e->d_name);
qsort(names, n, sizeof(char*), cmp);
for (int i = 0; i < n; i++) {
printf("%s\n", names[i]);
free(names[i]);
}
}
#include <sys/stat.h>
#include <time.h>
int cmp(const void *a, const void *b) {
struct stat sa, sb;
stat(*(char**)a, &sa);
stat(*(char**)b, &sb);
return sa.st_mtime - sb.st_mtime;
}
st_mtime:修改时间st_size:文件大小st_ctime:状态变更时间如果你只是想看排序结果:
ls # 默认排序
ls -t # 按时间
ls -S # 按大小
ls -v # 自然排序
| 需求 | 推荐方式 |
|---|---|
| 文件名排序 | scandir + alphasort |
| 时间/大小排序 | readdir + stat + qsort |
| 快速查看 | ls |
如果你告诉我:
我可以直接给你完整可跑代码。