温馨提示×

debian readdir如何排序结果

小樊
40
2026-09-16 12:43:06
栏目: 智能运维

在 Debian(或者说 Linux 下 C/C++ 编程)里,readdir() 本身不会保证任何顺序,它返回的是目录项在底层文件系统中的顺序(通常近似于创建顺序或哈希顺序),所以需要你自己排序。

下面给你几种常见做法,从“最常用”到“底层”。


一、最推荐:readdir + 自己排序(qsort)

基本思路

  1. 用 opendir() + readdir() 读取所有目录项
  2. 存到数组里
  3. 用 qsort() 排序
  4. 再使用

示例代码(按文件名排序)

#define _GNU_SOURCE
#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(".");
    if (!dir) return 1;

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

    while ((entry = readdir(dir))) {
        if (!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, ".."))
            continue;

        names = realloc(names, sizeof(char*) * (count + 1));
        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);
}

✅ 优点

  • 跨平台
  • 可控(可按时间、大小、inode 等排序)

二、按“自然顺序”排序(人类习惯)

如果你希望:

file1, file2, file10

而不是:

file1, file10, file2

可以使用 strverscmp()(GNU 扩展):

#define _GNU_SOURCE
#include <string.h>

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

⚠️ 仅在 glibc(Debian 默认)可用


三、按文件修改时间排序

#include <sys/stat.h>

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

四、不推荐但可用:scandir()

scandir() 自动帮你排序:

#include <dirent.h>

struct dirent **namelist;
int n = scandir(".", &namelist, NULL, alphasort);

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

✅ 简单
❌ 内存占用大,目录很大时不推荐


五、Shell 层面(如果你不是在写 C)

如果只是命令行:

ls -1 | sort
ls -1v      # 自然排序
ls -lt      # 按时间

总结

方式 是否排序 推荐度
readdir ❌ ⭐⭐⭐⭐(配合 qsort)
scandir ✅ ⭐⭐⭐
readdir + qsort ✅ ⭐⭐⭐⭐⭐

如果你能告诉我:

  • 用的是 C / C++ / Shell
  • 想按 名字 / 时间 / 大小 / 自然顺序

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

0 踩