温馨提示×

linux readdir如何按时间排

小樊
45
2026-09-17 20:08:06
栏目: 智能运维

在 Linux 下使用 readdir() 读取目录时,readdir 本身不会排序,它返回的是目录项(dirent)的“目录顺序”,和文件系统实现有关,不是按时间排序的。

如果你要“按时间排序”,正确做法是:

  1. 用 readdir() / opendir() 遍历目录
  2. 对每个文件调用 stat() 获取时间(如 st_mtime)
  3. 自己按时间排序

一、关键时间点(stat 结构体)

struct stat {
    time_t st_atime; // 最后访问时间
    time_t st_mtime; // 最后修改时间(最常用)
    time_t st_ctime; // 状态变更时间
};

一般“按时间排”指的是 st_mtime


二、示例代码(按修改时间排序)

1. 读取目录并保存文件名 + 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);

2. 按 mtime 排序

    // 按修改时间升序
    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;
            }
        }
    }

如果要降序(最新的在前),把 > 改成 <


3. 输出结果

    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() 获取


如果你需要:

  • 递归子目录按时间
  • 按访问时间 / 创建时间
  • 用 qsort 而不是冒泡
  • C++ / Rust 实现

可以告诉我,我可以直接给你对应版本。

0 踩