在C++中从一个目录复制文件到另一个目录
作者:野牛程序员:2023-06-28 16:26:30 C++阅读 3619
在 C++ 中,可以使用文件流(std::ifstream 和 std::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() 将源文件的内容复制到目标文件。最后,它检查复制操作是否成功,并返回相应的结果。
请确保将 sourceFile 和 destinationFile 替换为实际的源文件和目标文件的路径。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

- 上一篇:c++中TreeNode*root什么意思
- 下一篇:bat拷贝文件到另一个文件夹
