ubuntu

ubuntu readdir如何进行文件过滤

小樊
50
2025-09-10 06:36:54
栏目: 智能运维

在Ubuntu中,你可以使用readdir函数来读取目录中的文件。如果你想要对文件进行过滤,可以在读取文件后检查文件名是否满足你的条件。以下是一个简单的示例,展示了如何使用readdirdirent.h库来读取目录并过滤掉非.txt文件:

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

int main() {
    DIR *dir;
    struct dirent *entry;
    struct stat file_stat;

    dir = opendir("."); // 打开当前目录
    if (dir == NULL) {
        perror("opendir");
        return EXIT_FAILURE;
    }

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

        // 获取文件的完整路径
        char file_path[PATH_MAX];
        snprintf(file_path, sizeof(file_path), "./%s", entry->d_name);

        // 获取文件的状态信息
        if (stat(file_path, &file_stat) == -1) {
            perror("stat");
            continue;
        }

        // 检查文件是否为普通文件且扩展名为.txt
        if (S_ISREG(file_stat.st_mode) && strstr(entry->d_name, ".txt")) {
            printf("Found .txt file: %s\n", entry->d_name);
        }
    }

    closedir(dir);
    return EXIT_SUCCESS;
}

这个示例程序会打开当前目录,然后使用readdir函数读取目录中的每个条目。对于每个条目,它会检查文件名是否为.txt扩展名。如果是,它会打印出文件名。

请注意,这个示例使用了stat函数来获取文件的状态信息,以确保我们只处理普通文件(而不是目录或其他类型的文件)。strstr函数用于检查文件名中是否包含.txt字符串。

编译并运行这个程序,它将列出当前目录下所有的.txt文件。如果你想要过滤其他类型的文件,只需修改strstr函数中的字符串即可。

0
看了该问题的人还看了