温馨提示×

debian readdir怎样排序

小樊
40
2026-09-19 12:18:46
栏目: 智能运维

在 Debian(或者说 Linux 下 C/C++ 编程)里,readdir() 本身不会排序,返回的是目录项在文件系统里的顺序(通常是哈希或创建顺序,不确定)。
如果你需要“排序”,要在拿到结果后再自己排序。

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


一、readdir 默认行为

#include <dirent.h>

DIR *dir = opendir(".");
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
    printf("%s\n", entry->d_name);
}
closedir(dir);

⚠️ 顺序不可控,不能依赖


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

方法 1:用 scandir(最简单 ✅ 推荐)

#include <dirent.h>
#include <stdio.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);
  • alphasort:字典序排序
  • 自动过滤 . 和 ..(如果不想过滤可自定义 filter)

方法 2:readdir + qsort

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

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

int main() {
    DIR *dir = opendir(".");
    struct dirent *e;
    char *names[1024];
    int n = 0;

    while ((e = readdir(dir)))
        names[n++] = strdup(e->d_name);

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

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

三、按时间 / 大小排序(stat)

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

int cmp(const void *a, const void *b) {
    struct stat sa, sb;
    stat(*(char**)a, &sa);
    stat(*(char**)b, &sb);
    return sa.st_mtime - sb.st_mtime;
}
  • st_mtime:修改时间
  • st_size:文件大小
  • st_ctime:状态变更时间

四、命令行方式(非 C)

如果你只是想看排序结果:

ls          # 默认排序
ls -t       # 按时间
ls -S       # 按大小
ls -v       # 自然排序

总结

需求 推荐方式
文件名排序 scandir + alphasort
时间/大小排序 readdir + stat + qsort
快速查看 ls

如果你告诉我:

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

我可以直接给你完整可跑代码。

0 踩