在 Linux 下使用 readdir() 读取目录时,readdir() 本身不会保证任何排序顺序(通常是目录项在文件系统中的物理顺序)。如果你需要排序,通常做法是:
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(int argc, char *argv[]) {
const char *path = ".";
DIR *dir = opendir(path);
if (!dir) {
perror("opendir");
return 1;
}
struct dirent *entry;
char **names = NULL;
int count = 0, cap = 0;
while ((entry = readdir(dir)) != NULL) {
if (count >= cap) {
cap = cap ? cap * 2 : 16;
names = realloc(names, cap * sizeof(char *));
}
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]);
}
free(names);
return 0;
}
strcmp(a, b)
strcasecmp(a, b)
需要 stat():
struct stat sa, sb;
stat(a, &sa);
stat(b, &sb);
return sa.st_mtime - sb.st_mtime;
return sa.st_size - sb.st_size;
scandir()(自动排序)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:按名排序versionsort:按版本号排序(glibc)| 方法 | 是否排序 | 说明 |
|---|---|---|
readdir() |
❌ | 需手动排序 |
scandir() |
✅ | 推荐 |
readdir + qsort |
✅ | 灵活 |
如果你是 C / C++ / 嵌入式 / shell 调用 场景,我可以给你更具体的例子。