c++拷贝文件到指定目录
作者:野牛程序员:2023-07-06 12:04:18 C++阅读 2974
在C++中,你可以使用文件流 (fstream
) 来拷贝文件到指定目录。下面是一个简单的示例代码,演示如何拷贝文件到指定目录:
#include <iostream> #include <fstream> int main() { std::string sourcePath = "path/to/source/file.txt"; std::string destinationPath = "path/to/destination/directory/file.txt"; // 创建源文件流 std::ifstream sourceFile(sourcePath, std::ios::binary); if (!sourceFile) { std::cerr << "无法打开源文件!" << std::endl; return 1; } // 创建目标文件流 std::ofstream destinationFile(destinationPath, std::ios::binary); if (!destinationFile) { std::cerr << "无法创建目标文件!" << std::endl; return 1; } // 拷贝文件内容 destinationFile << sourceFile.rdbuf(); // 关闭文件流 sourceFile.close(); destinationFile.close(); std::cout << "文件拷贝完成!" << std::endl; return 0; }
在上述代码中,你需要将 sourcePath
替换为源文件的实际路径,将 destinationPath
替换为你希望拷贝到的目标目录和文件名。代码中使用的是二进制模式 (std::ios::binary
) 来处理文件,这样可以确保正确地拷贝二进制文件。
请注意,在运行此代码之前,请确保你的程序具有足够的权限来读取源文件和写入目标文件。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892
