当前位置:首页 C++ > 正文

c++移动目录下的所有图片文件到另一目录下

作者:野牛程序员:2023-07-16 15:01:07 C++阅读 2726

要在C++中移动目录下的所有图片文件到另一个目录,可以使用文件系统库(<filesystem>)来实现。以下是一个示例代码,展示了如何移动目录下的所有图片文件到另一个目录:

#include <iostream>
#include <filesystem>
#include <regex>

namespace fs = std::filesystem;

int main() {
    std::string sourceDir = "source_directory_path"; // 源目录路径
    std::string destinationDir = "destination_directory_path"; // 目标目录路径

    // 检查源目录是否存在
    if (!fs::exists(sourceDir) || !fs::is_directory(sourceDir)) {
        std::cout << "源目录不存在或不是一个目录。" << std::endl;
        return 1;
    }

    // 检查目标目录是否存在
    if (!fs::exists(destinationDir) || !fs::is_directory(destinationDir)) {
        std::cout << "目标目录不存在或不是一个目录。" << std::endl;
        return 1;
    }

    // 遍历源目录中的所有文件
    std::regex imageRegex(R"((.*\\.png$)|(.*\\.jpg$)|(.*\\.jpeg$))", std::regex::icase); // 图片文件的正则表达式
    for (const auto& entry : fs::directory_iterator(sourceDir)) {
        if (fs::is_regular_file(entry.path())) {
            std::string filename = entry.path().filename().string();
            // 检查文件是否匹配图片文件的正则表达式
            if (std::regex_match(filename, imageRegex)) {
                // 构建目标文件路径
                std::string destinationFile = destinationDir + "/" + filename;
                // 移动文件
                fs::rename(entry.path(), destinationFile);
                std::cout << "移动文件: " << filename << std::endl;
            }
        }
    }

    std::cout << "移动完成。" << std::endl;

    return 0;
}

请确保将 source_directory_path 替换为源目录的实际路径,将 destination_directory_path 替换为目标目录的实际路径。此代码假设源目录和目标目录都存在且为有效的目录。它使用正则表达式来匹配常见的图片文件扩展名(.png、.jpg 和 .jpeg),可以根据需要进行修改。移动文件的操作使用 std::filesystem::rename 函数来实现。

请注意,这段代码使用了C++17标准中引入的文件系统库(<filesystem>)。确保编译器支持C++17,并在编译时链接正确的库(例如,对于GCC编译器,需要使用 -lstdc++fs 选项进行链接)。


野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892
野牛程序员教少儿编程与信息学竞赛-微信|电话:15892516892
相关推荐

最新推荐

热门点击