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

c++ 复制文件到指定路径

作者:野牛程序员:2023-08-07 15:05:30 C++阅读 3355

在C++中,可以使用标准文件流来复制文件到指定路径。要复制文件,首先需要打开源文件和目标文件,然后从源文件读取数据并将其写入目标文件,最后关闭两个文件。

下面是一个简单的C++程序示例,演示如何复制文件到指定路径:

#include <iostream>
#include <fstream>

void copyFile(const std::string& sourcePath, const std::string& destinationPath) {
    std::ifstream sourceFile(sourcePath, std::ios::binary);
    if (!sourceFile) {
        std::cout << "Error opening source file: " << sourcePath << std::endl;
        return;
    }

    std::ofstream destinationFile(destinationPath, std::ios::binary);
    if (!destinationFile) {
        std::cout << "Error opening destination file: " << destinationPath << std::endl;
        return;
    }

    destinationFile << sourceFile.rdbuf();

    std::cout << "File copied successfully!" << std::endl;

    sourceFile.close();
    destinationFile.close();
}

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

    copyFile(sourceFilePath, destinationFilePath);

    return 0;
}

在这个示例中,copyFile函数接受源文件路径和目标文件路径作为参数,然后打开这两个文件并将源文件内容复制到目标文件。请注意,std::ios::binary标志用于以二进制模式打开文件,确保在复制过程中不会遇到文本文件中的换行符问题。

替换path/to/source/file.txtpath/to/destination/file.txt为实际的源文件路径和目标文件路径。运行这个程序将会把源文件复制到指定的目标路径。


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

最新推荐

热门点击