linux

readdir如何实现文件过滤功能

小樊
35
2025-04-14 12:23:20
栏目: 编程语言

readdir 是一个用于读取目录内容的函数,它本身并不提供直接的文件过滤功能。但是,你可以通过在读取目录内容后对每个文件进行检查来实现文件过滤。以下是一个使用 readdiropendir 在 C 语言中实现文件过滤功能的示例:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>

int is_directory(const char *path) {
    struct stat path_stat;
    if (stat(path, &path_stat) != 0) {
        return 0;
    }
    return S_ISDIR(path_stat.st_mode);
}

void list_files_with_extension(const char *directory, const char *extension) {
    DIR *dir = opendir(directory);
    if (dir == NULL) {
        perror("opendir");
        return;
    }

    struct dirent *entry;
    while ((entry = readdir(dir)) != NULL) {
        // 忽略当前目录和上级目录
        if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
            continue;
        }

        // 拼接文件路径
        char file_path[1024];
        snprintf(file_path, sizeof(file_path), "%s/%s", directory, entry->d_name);

        // 检查文件扩展名
        if (strstr(entry->d_name, extension) != NULL) {
            printf("%s\n", file_path);
        }
    }

    closedir(dir);
}

int main() {
    const char *directory = "/path/to/your/directory";
    const char *extension = ".txt";
    list_files_with_extension(directory, extension);
    return 0;
}

在这个示例中,我们定义了一个名为 list_files_with_extension 的函数,它接受一个目录路径和一个文件扩展名作为参数。该函数首先使用 opendir 打开目录,然后使用 readdir 读取目录中的每个条目。对于每个条目,我们检查它是否是一个目录(使用 is_directory 函数),然后检查它的扩展名是否与给定的扩展名匹配。如果匹配,我们将文件的完整路径打印出来。

main 函数中,我们调用 list_files_with_extension 函数,传入要搜索的目录路径和要过滤的文件扩展名。这个示例将打印出指定目录中所有具有给定扩展名的文件的完整路径。

0
看了该问题的人还看了