linux

Linux readdir如何自定义排序规则

小樊
49
2025-10-08 20:17:24
栏目: 智能运维

在Linux中,readdir函数用于读取目录中的文件和子目录

以下是一个使用readdir和自定义排序规则的示例:

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

// 自定义比较函数
int compare(const void *a, const void *b) {
    const char *str1 = *(const char **)a;
    const char *str2 = *(const char **)b;
    return strcmp(str1, str2);
}

int main() {
    DIR *dir;
    struct dirent *entry;
    char path[] = "/path/to/directory";
    char *files[100];

    dir = opendir(path);
    if (dir == NULL) {
        perror("opendir");
        return 1;
    }

    int i = 0;
    while ((entry = readdir(dir)) != NULL) {
        if (entry->d_type == DT_REG) { // 只添加普通文件
            files[i] = malloc(strlen(path) + strlen(entry->d_name) + 2);
            sprintf(files[i], "%s/%s", path, entry->d_name);
            i++;
        }
    }

    closedir(dir);

    // 使用qsort对文件名数组进行排序
    qsort(files, i, sizeof(char *), compare);

    // 打印排序后的文件名
    for (int j = 0; j < i; j++) {
        printf("%s\n", files[j]);
        free(files[j]);
    }

    return 0;
}

在这个示例中,我们首先使用opendir打开目录,然后使用readdir读取目录中的每个条目。我们将普通文件的路径存储在一个字符串数组中。接下来,我们使用qsort函数对字符串数组进行排序,自定义比较函数compare用于比较两个字符串。最后,我们打印排序后的文件名并释放分配的内存。

请注意,这个示例仅适用于普通文件。如果你需要处理其他类型的文件(如目录、符号链接等),你需要修改比较函数以满足你的需求。

0
看了该问题的人还看了