温馨提示×

CentOS readdir如何排序

小樊
43
2026-07-09 01:45:28
栏目: 智能运维

CentOS(Linux) 下,readdir 本身不会排序,它返回目录项的顺序是文件系统决定的(通常是 hash 或 inode 顺序)
如果你需要排序,必须在 应用层自己排序

下面分几种常见情况说明。


一、readdir 为什么没有顺序?

readdir() 读取的是 struct dirent,顺序由文件系统决定:

  • ext4:hash 顺序
  • xfs:接近 inode 顺序
  • tmpfs:不保证顺序

POSIX 不保证 readdir 的顺序


二、C 语言:readdir + 排序(推荐)

1️⃣ 读取目录

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

int main() {
    DIR *dir = opendir(".");
    struct dirent *entry;

    while ((entry = readdir(dir)) != NULL) {
        printf("%s\n", entry->d_name);
    }
    closedir(dir);
    return 0;
}

⚠️ 输出是无序的


2️⃣ 按文件名排序(常用)

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

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

int main() {
    DIR *dir = opendir(".");
    struct dirent *entry;

    const char *names[1024];
    int count = 0;

    while ((entry = readdir(dir)) != NULL && count < 1024) {
        names[count++] = strdup(entry->d_name);
    }
    closedir(dir);

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

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

    return 0;
}

按字母排序


3️⃣ 按时间 / inode 排序(高级)

需要 stat()

#include <sys/stat.h>
#include <sys/types.h>
#include <time.h>

然后比较:

struct stat st;
stat(name, &st);
st.st_mtime;  // 修改时间

三、Shell 中排序(不是 readdir,但常用)

按名称排序

ls -1 | sort

按时间排序

ls -lt

按大小排序

ls -lS

四、Python 中排序(对比参考)

import os

files = os.listdir('.')
files.sort()
print(files)

五、总结

场景 是否自动排序
readdir() ❌ 不排序
ls ✅ 默认排序
自己写程序 ✅ 需手动排序
按时间排序 ✅ 需 stat()

如果你能说明:

  • C / C++ / Shell
  • 想按 名称 / 时间 / 大小
  • 是否要 忽略 ...

我可以给你更精确的示例

0