温馨提示×

debian readdir如何按时间排序

小樊
40
2026-09-01 10:24:23
栏目: 智能运维

在 Debian(以及一般的 Linux)下,readdir() 本身不会排序,它只是按目录项在磁盘中的顺序返回结果。
如果你需要“按时间排序”,通常有两种做法:


一、在用户态对 readdir 结果排序(最常用)

基本思路

  1. opendir() + readdir() 获取文件名
  2. 对每个文件调用 stat() / lstat() 获取时间
  3. st_mtime(修改时间)排序

示例(C 语言,按修改时间排序)

#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;
}

✅ 这是最通用、最可控的方法,适合程序开发。


二、直接用 shell(非 readdir 编程)

如果你只是想查看按时间排序的文件:

ls -lt      # 按修改时间,最新在前
ls -ltr     # 最旧在前

底层 ls 也是 readdir + stat + sort


三、按不同“时间”排序

时间类型 stat 字段 说明
修改时间 st_mtime 文件内容修改
访问时间 st_atime 读取文件
状态时间 st_ctime 元数据变更

四、注意事项(Debian 常见坑)

  1. ... 会被 readdir 返回,通常需要过滤
  2. 使用 lstat() 可避免符号链接被跟随
  3. 文件名长度要防止溢出(用 d_name 动态长度)

总结

  • readdir() 不能直接按时间排序
  • ✅ 正确做法:readdir + stat + sort
  • ✅ 查看用 ls -lt
  • ✅ 编程用 qsort + st_mtime

如果你需要 C++ / Python / 递归目录 / 按时间倒序 的示例,也可以告诉我。

0