在 Linux 下使用 readdir() 读取目录时,readdir 本身不会排序,它返回的是目录项(dirent)的“目录顺序”,和文件系统实现有关,不是按时间排序的。
如果你要“按时间排序”,正确做法是:
readdir() / opendir() 遍历目录stat() 获取时间(如 st_mtime)struct stat {
time_t st_atime; // 最后访问时间
time_t st_mtime; // 最后修改时间(最常用)
time_t st_ctime; // 状态变更时间
};
一般“按时间排”指的是 st_mtime
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>
#include <time.h>
typedef struct {
char name[256];
time_t mtime;
} FileInfo;
int main(int argc, char *argv[]) {
const char *dir = ".";
DIR *dp = opendir(dir);
if (!dp) {
perror("opendir");
return 1;
}
FileInfo 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) == 0) {
strncpy(files[count].name, entry->d_name, 256);
files[count].mtime = st.st_mtime;
count++;
}
}
closedir(dp);
// 按修改时间升序
for (int i = 0; i < count - 1; i++) {
for (int j = i + 1; j < count; j++) {
if (files[i].mtime > files[j].mtime) {
FileInfo tmp = files[i];
files[i] = files[j];
files[j] = tmp;
}
}
}
如果要降序(最新的在前),把
>改成<
for (int i = 0; i < count; i++) {
printf("%s %s",
files[i].name,
ctime(&files[i].mtime));
}
return 0;
}
如果你只是命令行按时间排序:
ls -lt # 按修改时间(新→旧)
ls -ltr # 旧→新
如果你必须用 C 程序,那就只能 readdir + stat + sort
❌ readdir() 返回顺序 ≠ 时间顺序
❌ dirent->d_off 不是时间
✅ 时间必须靠 stat() 获取
如果你需要:
可以告诉我,我可以直接给你对应版本。