Linux readdir如何筛选特定文件类型

334
2025/4/10 12:33:02
栏目: 智能运维
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在Linux中,readdir函数用于读取目录中的文件和子目录。如果你想要筛选特定类型的文件,可以在读取到每个文件名后,检查其扩展名是否与你想要的类型匹配。

以下是一个使用C语言编写的示例,展示了如何使用readdir函数筛选特定文件类型(例如,只显示.txt文件):

#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;
    struct stat statbuf;
    char path[1024];

    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) {
        snprintf(path, sizeof(path), "%s/%s", argv[1], entry->d_name);

        if (stat(path, &statbuf) == -1) {
            perror("stat");
            continue;
        }

        if (S_ISREG(statbuf.st_mode)) {
            char *ext = strrchr(entry->d_name, '.');
            if (ext != NULL && strcmp(ext, ".txt") == 0) {
                printf("%s\n", entry->d_name);
            }
        }
    }

    closedir(dir);
    return EXIT_SUCCESS;
}

这个程序接受一个目录作为命令行参数,然后使用readdir函数读取目录中的每个条目。对于每个条目,我们使用stat函数获取文件的状态信息,然后检查它是否是一个常规文件(而不是目录、符号链接等)。如果是常规文件,我们检查其扩展名是否为.txt。如果是,我们打印文件名。

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

gcc filter_files.c -o filter_files

现在你可以使用以下命令运行程序,筛选特定类型的文件:

./filter_files <directory>

<directory>替换为你想要筛选文件的目录。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: Linux TigerVNC支持哪些加密方式