温馨提示×

linux readdir怎么排序

小樊
38
2026-09-20 22:40:31
栏目: 智能运维

在 Linux 下使用 readdir() 读取目录时,readdir 本身不会排序,返回的顺序依赖于文件系统在目录项里的存储顺序(通常是无序的)。
如果你想“排序”,正确做法是在 readdir 之后自己排序。

下面按常见需求给你几种做法。


一、readdir 基本用法(无序)

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

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

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

    closedir(dir);
    return 0;
}

⚠️ 输出顺序不保证有序


二、按文件名排序(最常用)

方法 1:先存起来,再用 qsort 排序

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

#define MAX_FILES 1024

int compare(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[MAX_FILES];
    int count = 0;

    while ((entry = readdir(dir)) && count < MAX_FILES) {
        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((void *)names[i]);
    }
    return 0;
}

✅ 按 字典序(ASCII)排序


三、按数字名排序(如 file1, file2, file10)

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

或更严谨地用 strtol


四、按文件修改时间排序(需要 stat)

#include <sys/stat.h>

struct FileInfo {
    char name[256];
    time_t mtime;
};

int compare(const void *a, const void *b) {
    return ((struct FileInfo *)a)->mtime - ((struct FileInfo *)b)->mtime;
}

读取时:

struct stat st;
stat(entry->d_name, &st);
info[i].mtime = st.st_mtime;
strcpy(info[i].name, entry->d_name);

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

1️⃣ 用 scandir(推荐)

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

int main() {
    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);
}

✅ 自动按文件名排序 ✅ 比 readdir + qsort 简单


2️⃣ Shell 里直接排序

ls -1 | sort

六、总结

需求 推荐方式
简单文件名排序 scandir + alphasort
自定义排序 readdir + qsort
按时间/大小 readdir + stat
快速脚本 `ls

如果你告诉我:

  • 用 C / C++ / Shell
  • 按 名字 / 时间 / 大小 / 数字

我可以直接给你一份完整可编译代码。

0 踩