温馨提示×

ubuntu readdir怎样排序结果

小樊
38
2026-09-18 18:27:54
栏目: 智能运维

在 Ubuntu(Linux)下,使用 readdir() 读取目录时,readdir() 本身不会保证任何排序顺序(通常依赖于文件系统在目录项里的存储顺序,往往是“乱的”或按 inode 顺序)。

所以常见做法有两类:


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

用 readdir() 读取所有文件名,存到数组里,然后再排序。

示例(按文件名排序,C 语言)

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

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

    while ((entry = readdir(dir)) != NULL) {
        names = realloc(names, sizeof(char*) * (count + 1));
        names[count] = strdup(entry->d_name);
        count++;
    }
    closedir(dir);

    // 按字典序排序
    qsort(names, count, sizeof(char*),
          (int (*)(const void*, const void*))strcmp);

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

二、按不同规则排序

1️⃣ 按文件名(默认)

strcmp(a, b)

2️⃣ 按文件修改时间

struct stat sa, sb;
stat(a, &sa);
stat(b, &sb);
return sa.st_mtime - sb.st_mtime;

3️⃣ 按文件大小

return sa.st_size - sb.st_size;

4️⃣ 忽略 . 和 ..

if (strcmp(entry->d_name, ".") == 0 ||
    strcmp(entry->d_name, "..") == 0)
    continue;

三、更简单的替代方案(不写 C)

如果你不是必须写 C 程序:

Shell(最简单)

ls -1 | sort
ls -lt      # 按时间
ls -lS      # 按大小

C++(如果允许)

for (auto &p : std::filesystem::directory_iterator("."))
    std::cout << p.path() << "\n";

然后直接用 std::sort


四、重要说明

  • ❌ readdir() 不支持排序参数
  • ✅ 排序必须在读取后自己做
  • ✅ 如果需要稳定顺序,一定要排序

如果你告诉我:

  • 用 C / C++ / Python
  • 按 名称 / 时间 / 大小
  • 是否要递归

我可以给你更精确的代码。

0 踩