在 Debian(Linux)下,如果你说的是 用 readdir() 读取目录后按时间排序,需要注意:
readdir()本身不保证顺序,也不直接提供排序功能
需要:
- 用
readdir()读取所有目录项- 用
stat()/lstat()获取时间- 自己排序(如
qsort)
常用时间字段(在 struct stat 中):
st_mtime:文件内容修改时间(最常用)st_ctime:状态改变时间st_atime:访问时间#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>
#include <errno.h>
struct file_info {
char name[256];
time_t mtime;
};
int compare(const void *a, const void *b) {
const struct file_info *fa = a;
const struct file_info *fb = b;
return (fa->mtime - fb->mtime);
}
int main(int argc, char *argv[]) {
const char *dir = argc > 1 ? argv[1] : ".";
DIR *dp = opendir(dir);
if (!dp) {
perror("opendir");
return 1;
}
struct file_info files[1024];
int count = 0;
struct dirent *entry;
while ((entry = readdir(dp)) != NULL) {
if (strcmp(entry->d_name, ".") == 0 ||
strcmp(entry->d_name, "..") == 0)
continue;
char path[512];
snprintf(path, sizeof(path), "%s/%s", dir, entry->d_name);
struct stat st;
if (stat(path, &st) == -1)
continue;
strncpy(files[count].name, entry->d_name, 255);
files[count].mtime = st.st_mtime;
count++;
}
closedir(dp);
qsort(files, count, sizeof(struct file_info), compare);
for (int i = 0; i < count; i++) {
printf("%s\n", files[i].name);
}
return 0;
}
ls -lt
ls -ltr
ls -lc # ctime
ls -lu # atime
❌ readdir() 返回顺序 ≠ 时间顺序
❌ 不能仅靠 dirent 排序
✅ 必须 stat() 后排序
你可以告诉我:
我可以直接给你对应版本代码。