在 Debian(或任何 Linux)上,readdir 本身不排序,它返回目录项的顺序是文件系统决定的(通常是目录项在磁盘上的存储顺序,不一定按字母序)。
如果你想“排序”,有几种常见做法:
readdir + 排序opendir / readdir 读取所有目录项qsort 排序#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.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 = NULL;
int count = 0;
while ((entry = readdir(dir)) != NULL) {
names = realloc(names, sizeof(char*) * (count + 1));
names[count] = strdup(entry->d_name);
count++;
}
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;
}
. 和 ..通常排序前要过滤:
if (strcmp(entry->d_name, ".") == 0 ||
strcmp(entry->d_name, "..") == 0)
continue;
用 stat() 读取 st_mtime 再排序
用 stat() 读取 st_size
如果你只是想在命令行排序:
ls -1 | sort
ls -lt # 按时间
ls -lS # 按大小
readdir 不排序readdir + 数组 + qsort如果你告诉我:
我可以给你更精确的代码。