温馨提示×

使用C++ Glob进行文件过滤的方法

c++
小樊
88
2024-08-19 19:06:30
栏目: 编程语言

在C++中,可以使用glob()函数来进行文件过滤。glob()函数定义在<glob.h>头文件中,用于匹配指定模式的文件路径。

以下是一个简单的示例代码,使用glob()函数来过滤文件路径:

#include <iostream>
#include <glob.h>
#include <vector>

int main() {
    std::vector<std::string> files;
    glob_t glob_result;

    // 匹配所有文件名符合 "*.txt" 格式的文件
    if(glob("*.txt", 0, NULL, &glob_result) == 0) {
        for(unsigned int i=0; i<glob_result.gl_pathc; ++i){
            files.push_back(std::string(glob_result.gl_pathv[i]));
        }
    }

    globfree(&glob_result);

    // 输出符合条件的文件路径
    for(const std::string& file : files) {
        std::cout << file << std::endl;
    }

    return 0;
}

在上面的示例代码中,glob()函数会将所有匹配*.txt格式的文件路径存储在glob_result.gl_pathv中,然后将这些文件路径存储在files向量中。最后,遍历files向量并输出符合条件的文件路径。

需要注意的是,在使用glob()函数后,需要使用globfree(&glob_result)函数来释放glob_result结构体所占用的内存。

0