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

C++移动文件到指定目录并修改文件名

作者:野牛程序员:2023-07-16 14:46:31 C++阅读 2723

在C++中,可以使用标准库中的文件操作函数来移动文件到指定目录并修改文件名。以下是一个示例代码,演示如何完成这个任务:

#include <iostream>
#include <filesystem>

namespace fs = std::filesystem;

int main() {
    std::string sourceFilePath = "path/to/source/file.txt";
    std::string destinationDirectory = "path/to/destination/";
    std::string newFileName = "new_file_name.txt";

    // 构造源文件的完整路径
    fs::path sourcePath(sourceFilePath);

    // 构造目标文件的完整路径
    fs::path destinationPath = fs::path(destinationDirectory) / newFileName;

    try {
        // 移动文件
        fs::rename(sourcePath, destinationPath);
        std::cout << "文件移动成功!" << std::endl;
    } catch (const fs::filesystem_error& e) {
        std::cerr << "文件移动失败: " << e.what() << std::endl;
    }

    return 0;
}

在上面的代码中,你需要将sourceFilePath设置为源文件的路径,destinationDirectory设置为目标目录的路径,newFileName设置为文件移动后的新名称。代码使用std::filesystem命名空间来操作文件和路径。

请注意,std::filesystem是C++17引入的新特性,因此你的编译器必须支持C++17标准才能编译和运行上述代码。


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

最新推荐

热门点击