在 Ubuntu(Linux)下,readdir 本身不会排序,它返回目录项是内核/文件系统顺序的(通常看起来是乱的)。
如果你要对文件排序,一般有两种做法:
readdir + 自己排序(最常见)opendir + readdir 读取所有文件名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 **files = NULL;
int count = 0;
while ((entry = readdir(dir)) != NULL) {
if (entry->d_name[0] == '.') continue; // 忽略隐藏文件
files = realloc(files, sizeof(char*) * (count + 1));
files[count] = strdup(entry->d_name);
count++;
}
closedir(dir);
qsort(files, count, sizeof(char*), compare);
for (int i = 0; i < count; i++) {
printf("%s\n", files[i]);
free(files[i]);
}
free(files);
}
#include <sys/stat.h>
int compare_time(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;
}
int compare_size(const void *a, const void *b) {
struct stat sa, sb;
stat(*(const char**)a, &sa);
stat(*(const char**)b, &sb);
return sa.st_size - sb.st_size;
}
如果你是 shell / 脚本:
ls -1 | sort
ls -lt # 按时间
ls -lS # 按大小
如果你是 C++:
#include <filesystem>
for (auto &p : std::filesystem::directory_iterator("."))
std::cout << p.path() << "\n";
(C++17 可直接排序,比 C 方便很多)
✅ readdir 不排序
✅ 正确做法:readdir + qsort
✅ 可按:名称 / 时间 / 大小 / 自定义规则
如果你告诉我:
我可以直接给你完整代码。