在 Debian(以及一般的 Linux)下,readdir() 本身不会排序,它只是按目录项在磁盘中的顺序返回结果。
如果你需要“按时间排序”,通常有两种做法:
opendir() + readdir() 获取文件名stat() / lstat() 获取时间st_mtime(修改时间)排序#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>
#include <time.h>
struct file_entry {
char name[256];
time_t mtime;
};
int compare(const void *a, const void *b) {
return ((struct file_entry *)a)->mtime -
((struct file_entry *)b)->mtime;
}
int main() {
DIR *dir = opendir(".");
struct dirent *entry;
struct file_entry files[1024];
int count = 0;
while ((entry = readdir(dir)) != NULL) {
struct stat st;
if (stat(entry->d_name, &st) == 0) {
strcpy(files[count].name, entry->d_name);
files[count].mtime = st.st_mtime;
count++;
}
}
closedir(dir);
qsort(files, count, sizeof(struct file_entry), compare);
for (int i = 0; i < count; i++)
printf("%s\n", files[i].name);
return 0;
}
✅ 这是最通用、最可控的方法,适合程序开发。
如果你只是想查看按时间排序的文件:
ls -lt # 按修改时间,最新在前
ls -ltr # 最旧在前
底层 ls 也是 readdir + stat + sort。
| 时间类型 | stat 字段 | 说明 |
|---|---|---|
| 修改时间 | st_mtime |
文件内容修改 |
| 访问时间 | st_atime |
读取文件 |
| 状态时间 | st_ctime |
元数据变更 |
. 和 .. 会被 readdir 返回,通常需要过滤lstat() 可避免符号链接被跟随d_name 动态长度)readdir() 不能直接按时间排序readdir + stat + sortls -ltqsort + st_mtime如果你需要 C++ / Python / 递归目录 / 按时间倒序 的示例,也可以告诉我。