温馨提示×

ubuntu readdir如何排序结果

小樊
43
2026-10-18 08:00:02
栏目: 智能运维

在 Ubuntu(Linux)下使用 readdir 读取目录时,readdir 本身不会排序,返回的顺序取决于文件系统在目录项中的存储顺序(通常是无序的)。

要对结果排序,常见做法有下面几种:


一、使用 readdir + 手动排序(最常用)

基本思路

  1. 用 opendir / readdir 读取所有文件名
  2. 存入数组
  3. 使用 qsort 或 C++ 的 sort 排序

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

#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() {
    DIR *dir = opendir(".");
    struct dirent *entry;
    char *names[1024];
    int count = 0;

    while ((entry = readdir(dir)) != NULL) {
        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;
}

二、按文件修改时间排序(使用 stat)

#include <sys/stat.h>

int compare_time(const void *a, const void *b) {
    struct stat sa, sb;
    stat(*(const char **)a, &sa);
    stat(*(const char **)b, &sb);
    return difftime(sa.st_mtime, sb.st_mtime);
}

三、忽略 . 和 ..

通常排序前会过滤:

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

四、如果不必须用 readdir(更简单)

1. Shell

ls -1 | sort

2. C++(推荐)

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

(C++17,自动无序,可配合 vector + sort)


总结

  • ✅ readdir 不排序
  • ✅ 必须自己收集后排序
  • ✅ 常用:qsort / std::sort
  • ✅ 可按:名称、时间、大小等排序

如果你有特定排序规则(如中文、数字自然排序、隐藏文件处理),可以告诉我,我给你写对应代码。

0 踩