温馨提示×

centos readdir怎排序

小樊
38
2026-09-18 07:21:29
栏目: 智能运维

CentOS(Linux) 下,readdir 本身不会排序,它返回的文件顺序是不确定的(依赖于文件系统的实现)。

如果你需要对 readdir 读取的结果进行排序,常见做法有下面几种:


一、在 C 程序中排序(最正规方式)

1. 使用 readdir + scandir(推荐)

scandir 本身支持排序函数:

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

int main() {
    struct dirent **namelist;
    int n = scandir(".", &namelist, NULL, alphasort);
    if (n < 0) {
        perror("scandir");
        return 1;
    }

    for (int i = 0; i < n; i++) {
        printf("%s\n", namelist[i]->d_name);
        free(namelist[i]);
    }
    free(namelist);
    return 0;
}

alphasort:按字母排序
versionsort:按版本号排序(CentOS 较新 glibc 支持)


2. 使用 readdir + qsort(手动排序)

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

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

int main() {
    DIR *dir = opendir(".");
    struct dirent *entry;
    char *names[1024];
    int count = 0;

    while ((entry = readdir(dir)) && count < 1024) {
        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]);
    }
    return 0;
}

二、Shell 中排序(非编程方式)

如果你只是想在命令行里用:

ls -1 | sort

或:

for f in *; do echo "$f"; done | sort

三、常见问题说明

❓ ext4 / xfs 下 readdir 顺序

  • 不是按名字排序
  • 可能是 inode 或目录项顺序

❓ 想按时间 / 大小排序

  • 需要 stat() 获取信息后再排序

总结

方式 是否排序 说明
readdir 不排序
scandir + alphasort 推荐
readdir + qsort 灵活
shell sort 非程序

如果你能说明是 C / C++ / Shell / 内核模块,我可以给你更精确的示例。

0