温馨提示×

centos readdir怎样排序

小樊
36
2026-09-12 01:34:15
栏目: 智能运维

在 CentOS(本质上是 Linux 下使用 glibc 的 readdir / readdir_r)中,readdir() 本身返回的目录项顺序是不确定的(通常是文件系统内部的顺序,不一定是字母序)
如果你需要“排序”,正确做法是用 readdir 读取所有条目,然后自己排序

下面按常见需求给你几种做法。


一、C 语言:readdir + 手动排序(最标准)

示例:按文件名排序(字母序)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>

int compare(const void *a, const void *b) {
    return strcmp(*(const char **)a, *(const char **)b);
}

int main(int argc, char *argv[]) {
    const char *path = ".";
    DIR *dir = opendir(path);
    if (!dir) {
        perror("opendir");
        return 1;
    }

    struct dirent *entry;
    char **names = NULL;
    int count = 0, cap = 0;

    while ((entry = readdir(dir)) != NULL) {
        if (count >= cap) {
            cap = cap ? cap * 2 : 16;
            names = realloc(names, cap * sizeof(char *));
        }
        names[count++] = strdup(entry->d_name);
    }
    closedir(dir);

    qsort(names, count, sizeof(char *), compare);

    for (int i = 0; i < count; i++) {
        printf("%s\n", names[i]);
        free(names[i]);
    }
    free(names);

    return 0;
}

✅ 优点

  • 不依赖系统
  • 可控(可改时间排序、大小排序)

二、按“修改时间”排序(常见需求)

stat() 获取时间:

struct stat st;
stat(entry->d_name, &st);
st.st_mtime  // 修改时间

然后按 st_mtime 排序即可。


三、Shell 层:CentOS 直接用命令(不用写代码)

如果你只是想看排序结果

ls -1        # 按名排序
ls -lt       # 按修改时间
ls -lS       # 按大小

四、常见误区

readdir() 返回顺序 ≠ 排序
❌ 不同文件系统(ext4 / xfs)顺序可能不同
❌ 不要依赖 readdir 的顺序写逻辑


五、总结

需求 做法
文件名排序 readdir + qsort
时间排序 readdir + stat
只是查看 ls
高性能 读取后一次性排序

如果你是 C / C++ / Python / 特定场景(如递归目录),可以告诉我,我给你对应版本。

0