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

c++复制文件到另一目录

作者:野牛程序员:2023-08-30 09:28:08 C++阅读 3265

在C++中,可以使用文件流(fstream)来实现将文件复制到另一个目录。以下是一个简单的示例代码,演示如何复制一个文件到另一个目录:

#include <iostream>
#include <fstream>

int main() {
    // 原始文件路径和目标文件路径
    std::string sourceFilePath = "path_to_source_file/source.txt";
    std::string targetFilePath = "path_to_target_directory/target.txt";

    // 打开原始文件以读取内容
    std::ifstream sourceFile(sourceFilePath, std::ios::binary);
    if (!sourceFile) {
        std::cout << "无法打开源文件" << std::endl;
        return 1;
    }

    // 创建目标文件并打开以写入内容
    std::ofstream targetFile(targetFilePath, std::ios::binary);
    if (!targetFile) {
        std::cout << "无法创建目标文件" << std::endl;
        return 1;
    }

    // 逐个字节复制内容
    char byte;
    while (sourceFile.get(byte)) {
        targetFile.put(byte);
    }

    // 关闭文件流
    sourceFile.close();
    targetFile.close();

    std::cout << "文件复制完成" << std::endl;

    return 0;
}

在上面的代码中,需要将 path_to_source_file/source.txt 替换为实际的源文件路径,将 path_to_target_directory/target.txt 替换为实际的目标文件路径。这段代码会逐个字节复制源文件的内容到目标文件中,实现了文件的复制。

请注意,这只是一个基本的示例,可能不适用于所有情况,特别是对于大文件来说效率可能不高。


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

最新推荐

热门点击