阅读量:3
在C++中,你可以使用标准库中的头文件来实现文件复制
#include
#include
#include
bool copyFile(const std::string& source, const std::string& destination) {
// 打开源文件以读取
std::ifstream src(source, std::ios::binary);
if (!src) {
std::cerr << "无法打开源文件: " << source << std::endl;
return false;
}
// 打开目标文件以写入
std::ofstream dest(destination, std::ios::binary);
if (!dest) {
std::cerr << "无法打开目标文件: " << destination << std::endl;
return false;
}
// 复制文件内容
dest.write(src.rdbuf(), src.tellg());
if (!dest) {
std::cerr << "复制文件失败" << std::endl;
return false;
}
// 重置文件指针到开始位置
src.seekg(0, std::ios::beg);
src.clear();
// 将源文件指针设置到开始位置
dest.seekp(0, std::ios::beg);
dest.clear();
// 关闭文件
src.close();
dest.close();
std::cout << "文件复制成功" << std::endl;
return true;
}
int main() {
std::string source = "source.txt";
std::string destination = "destination.txt";
if (copyFile(source, destination)) {
std::cout << "源文件: " << source << std::endl;
std::cout << "目标文件: " << destination << std::endl;
} else {
std::cerr << "文件复制失败" << std::endl;
}
return 0;
}
这个示例中的copyFile函数接受两个std::string参数,分别表示源文件和目标文件的路径。函数首先打开源文件以读取,然后打开目标文件以写入。接下来,它使用rdbuf()方法获取源文件的缓冲区,并将其写入目标文件。最后,关闭文件并返回成功或失败的消息。
以上就是关于“如何通过c++文件函数实现文件复制”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm