温馨提示×

Linux readdir如何实现过滤功能

小樊
34
2025-12-19 07:45:33
栏目: 智能运维

在Linux中,readdir函数用于读取目录中的文件和子目录。要实现过滤功能,您可以在调用readdir之后对返回的dirent结构体进行检查,根据需要决定是否处理某个文件或子目录。

以下是一个简单的示例,展示了如何使用readdirdirent.h库实现过滤功能:

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

int main(int argc, char *argv[]) {
    DIR *dir;
    struct dirent *entry;
    char path[1024];

    if (argc != 2) {
        fprintf(stderr, "Usage: %s <directory>\n", argv[0]);
        return EXIT_FAILURE;
    }

    // 打开目录
    dir = opendir(argv[1]);
    if (!dir) {
        perror("opendir");
        return EXIT_FAILURE;
    }

    // 遍历目录中的文件和子目录
    while ((entry = readdir(dir)) != NULL) {
        // 跳过当前目录(.)和上级目录(..)
        if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
            continue;
        }

        // 构建文件的完整路径
        snprintf(path, sizeof(path), "%s/%s", argv[1], entry->d_name);

        // 获取文件信息
        struct stat file_stat;
        if (stat(path, &file_stat) == -1) {
            perror("stat");
            continue;
        }

        // 检查文件类型和名称,根据需要进行过滤
        if (S_ISREG(file_stat.st_mode) && strstr(entry->d_name, "txt")) {
            printf("Regular file with 'txt' extension: %s\n", entry->d_name);
        } else if (S_ISDIR(file_stat.st_mode)) {
            printf("Directory: %s\n", entry->d_name);
        }
    }

    // 关闭目录
    closedir(dir);
    return EXIT_SUCCESS;
}

在这个示例中,我们遍历指定目录中的所有文件和子目录,并检查它们的类型和名称。如果文件是常规文件并且名称包含"txt",则打印出来。如果是一个目录,则打印目录名。您可以根据需要修改过滤条件。

编译并运行这个程序,传入一个目录作为参数,它将输出符合条件的文件和子目录。

0