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

在C++中从一个目录复制文件到另一个目录

作者:野牛程序员:2023-06-28 16:26:30 C++阅读 3433

在 C++ 中,可以使用文件流(std::ifstreamstd::ofstream)来从一个目录复制文件到另一个目录。下面是一个示例代码,演示了如何实现这一操作:

#include <iostream>
#include <fstream>

bool copyFile(const std::string& sourceFile, const std::string& destinationFile) {
    std::ifstream src(sourceFile, std::ios::binary);
    if (!src) {
        std::cout << "无法打开源文件:" << sourceFile << std::endl;
        return false;
    }

    std::ofstream dest(destinationFile, std::ios::binary);
    if (!dest) {
        std::cout << "无法创建目标文件:" << destinationFile << std::endl;
        return false;
    }

    dest << src.rdbuf();

    if (src.fail() || dest.fail()) {
        std::cout << "文件复制失败。" << std::endl;
        return false;
    }

    std::cout << "文件复制成功。" << std::endl;
    return true;
}

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

    if (copyFile(sourceFile, destinationFile)) {
        std::cout << "文件复制成功。" << std::endl;
    } else {
        std::cout << "文件复制失败。" << std::endl;
    }

    return 0;
}

在上述代码中,copyFile 函数接受源文件路径和目标文件路径作为参数。它首先使用 std::ifstream 打开源文件,并检查是否成功打开。然后,它使用 std::ofstream 创建目标文件,并检查是否成功创建。接下来,它使用 dest << src.rdbuf() 将源文件的内容复制到目标文件。最后,它检查复制操作是否成功,并返回相应的结果。

请确保将 sourceFiledestinationFile 替换为实际的源文件和目标文件的路径。


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

最新推荐

热门点击