在 Ubuntu(Linux)下使用 readdir 读取目录时,readdir 本身不会排序,返回的顺序取决于文件系统在目录项中的存储顺序(通常是无序的)。
要对结果排序,常见做法有下面几种:
readdir + 手动排序(最常用)opendir / readdir 读取所有文件名qsort 或 C++ 的 sort 排序#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[1024];
int count = 0;
while ((entry = readdir(dir)) != NULL) {
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(names[i]);
}
return 0;
}
stat)#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 difftime(sa.st_mtime, sb.st_mtime);
}
. 和 ..通常排序前会过滤:
if (strcmp(entry->d_name, ".") == 0 ||
strcmp(entry->d_name, "..") == 0)
continue;
readdir(更简单)ls -1 | sort
#include <filesystem>
for (auto &p : std::filesystem::directory_iterator("."))
std::cout << p.path().filename() << "\n";
(C++17,自动无序,可配合 vector + sort)
readdir 不排序qsort / std::sort如果你有特定排序规则(如中文、数字自然排序、隐藏文件处理),可以告诉我,我给你写对应代码。