温馨提示×

debian readdir如何按时间排

小樊
42
2026-09-07 10:27:37
栏目: 智能运维

在 Debian(Linux)下,如果你说的是 readdir() 读取目录后按时间排序,需要注意:

readdir() 本身不保证顺序,也不直接提供排序功能
需要:

  1. readdir() 读取所有目录项
  2. stat() / lstat() 获取时间
  3. 自己排序(如 qsort

一、基本概念

常用时间字段(在 struct stat 中):

  • st_mtime:文件内容修改时间(最常用)
  • st_ctime:状态改变时间
  • st_atime:访问时间

二、C 语言示例(readdir + 按 mtime 排序)

示例:按修改时间排序(升序)

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

三、如果你只是想在 shell 里按时间排

按修改时间(新 → 旧)

ls -lt

旧 → 新

ls -ltr

按文件创建/变更时间

ls -lc   # ctime
ls -lu   # atime

四、常见误区

readdir() 返回顺序 ≠ 时间顺序
❌ 不能仅靠 dirent 排序
✅ 必须 stat() 后排序


五、如果你愿意

你可以告诉我:

  • 用的是 C / C++ / Python / Shell
  • 修改时间 / 创建时间 / 访问时间
  • 是否需要 递归子目录

我可以直接给你对应版本代码。

0