温馨提示×

readdir在Linux中如何实现文件过滤

小樊
41
2025-11-05 13:56:08
栏目: 智能运维

在Linux中,readdir函数用于读取目录中的条目。如果你想要实现文件过滤,可以在调用readdir之后对返回的dirent结构体进行筛选。以下是一个简单的示例,展示了如何使用readdir函数过滤掉目录中的非普通文件(例如,只显示普通文件):

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

int is_regular_file(const char *path) {
    struct stat path_stat;
    if (stat(path, &path_stat) != 0) {
        perror("stat");
        return 0;
    }
    return S_ISREG(path_stat.st_mode);
}

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

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

    dir = opendir(argv[1]);
    if (dir == NULL) {
        perror("opendir");
        return EXIT_FAILURE;
    }

    while ((entry = readdir(dir)) != NULL) {
        if (is_regular_file(entry->d_name)) {
            printf("%s\n", entry->d_name);
        }
    }

    closedir(dir);
    return EXIT_SUCCESS;
}

在这个示例中,我们首先定义了一个is_regular_file函数,该函数接受一个文件路径作为参数,并使用stat函数获取文件的元数据。然后,我们检查文件的类型是否为普通文件(S_ISREG宏)。

main函数中,我们打开一个目录,然后使用readdir函数读取目录中的每个条目。对于每个条目,我们调用is_regular_file函数来检查它是否为普通文件。如果是,我们将其名称打印到屏幕上。

要编译此程序,请将其保存为list_regular_files.c,然后运行以下命令:

gcc -o list_regular_files list_regular_files.c

现在,你可以使用这个程序来列出目录中的所有普通文件:

./list_regular_files /path/to/directory

你可以根据需要修改is_regular_file函数来实现其他过滤条件,例如只显示特定扩展名的文件或隐藏文件等。

0