温馨提示×

ubuntu readdir怎么排序结果

小樊
49
2026-09-30 18:24:45
栏目: 智能运维

在 Ubuntu(Linux)下使用 readdir 读取目录时,readdir 本身是不会排序的,它返回的顺序依赖于底层文件系统(通常是目录项在磁盘上的存储顺序,看起来是“乱的”)。

如果你需要排序结果,常见做法有:


一、用 readdir 读取后再排序(最常用)

1. 使用 scandir(推荐)

scandir 可以直接排序,比 readdir 方便很多。

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

int main() {
    struct dirent **namelist;
    int n = scandir(".", &namelist, NULL, alphasort);
    if (n < 0) {
        perror("scandir");
        return 1;
    }

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

✅ alphasort:按字母排序
✅ versionsort:按版本号排序(Ubuntu 支持)


2. 使用 readdir + 手动排序

如果你必须用 readdir:

#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.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 = 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*), compare);

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

二、不排序,但想“看起来有序”

1. 管道给 sort

ls | sort

2. C 程序里调用 shell

system("ls | sort");

(不推荐,除非简单脚本)


三、排序方式总结

方法 是否排序 推荐度
readdir ❌ 不排序 ⭐⭐
scandir + alphasort ✅ 字母序 ⭐⭐⭐⭐⭐
readdir + qsort ✅ 自定义 ⭐⭐⭐⭐
system("ls") ✅ ⭐

如果你有特定排序需求(比如:

  • 按修改时间
  • 按文件大小
  • 忽略 . 和 ..
  • 只列某种文件

可以告诉我,我给你写对应代码。

0 踩