温馨提示×

如何结合C++ Glob进行文件重命名

c++
小樊
82
2024-08-19 19:12:29
栏目: 编程语言

您可以使用C++的std::filesystem库来结合glob进行文件重命名。下面是一个简单的示例代码:

#include <iostream>
#include <string>
#include <filesystem>
#include <glob.h>

void renameFiles(const std::string& pattern, const std::string& newName)
{
    glob_t globResult;
    glob(pattern.c_str(), GLOB_TILDE, NULL, &globResult);

    for(size_t i = 0; i < globResult.gl_pathc; ++i)
    {
        std::filesystem::path oldPath(globResult.gl_pathv[i]);
        std::filesystem::path newPath = oldPath.parent_path() / newName;

        try
        {
            std::filesystem::rename(oldPath, newPath);
        }
        catch(const std::exception& e)
        {
            std::cerr << e.what() << std::endl;
        }
    }

    globfree(&globResult);
}

int main()
{
    std::string pattern = "path/to/files/*.txt";
    std::string newName = "newFileName.txt";

    renameFiles(pattern, newName);

    return 0;
}

在这个示例中,renameFiles函数会通过glob函数匹配指定模式的文件,并将它们重命名为新的文件名。您可以将要匹配的文件模式和新的文件名作为参数传递给renameFiles函数。

0