温馨提示×

ubuntu readdir怎样排序

小樊
44
2026-10-12 11:04:27
栏目: 智能运维

在 Ubuntu(Linux)下,readdir 本身不会排序,它返回目录项是内核/文件系统顺序(通常是目录项在磁盘上的顺序,不保证任何逻辑顺序)。

如果你想要排序,需要自己排序。


一、readdir 为什么没有顺序?

readdir() / readdir_r() 来自 <dirent.h>,示例:

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

输出顺序可能是:

file3
file1
file10
file2

二、常见排序方式

✅ 1. 按文件名排序(最常用)

先把文件名存起来,再用 qsort 排序。

#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]);
    }
}

✅ 2. 按自然语言顺序排序(file1, file2, file10)

使用 alphasort 或 scandir:

#include <stdio.h>
#include <dirent.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);
}

✅ scandir 内部已经帮你排序了


✅ 3. 按修改时间排序

读取 stat 后排序:

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

用 stat() 获取 st_mtime,然后 qsort


✅ 4. Shell 中排序(非 C)

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

三、总结

需求 方法
文件名排序 qsort + strcmp
简单排序 scandir + alphasort
时间排序 stat + qsort
Shell `ls

如果你是用 C / C++ / Python / shell 或需要中文排序 / 忽略 . 文件,可以告诉我,我可以给你更具体的代码。

0 踩