# 【C++编程实战】多线程学习——双线程复制文件

欢迎关注,本专栏主要更新C++基础编程,STL编程,OPP编程,设计模式,多线程编程,网络编程,Linux系统编程,mysql接口,常用的第三方库(如jsoncpp,openssl,opencv等),拥有丰富的实例练习代码,欢迎订阅该专栏!(等该专栏建设成熟后将开始收费,快快上车吧~~)

【C++编程实战】多线程学习——双线程复制文件

具体的思路是,首先通过函数来获得文件的实际大小,然后得到文件中间的位置,接着通过
把得到的每个线程需要负责的复制位置传递到线程内部,执行复制函数即可。

#include <iostream>
#include <fstream>
#include <thread>
#include <vector>
#include <string>

void copyFileThread(std::string srcFile, std::string destFile, int start, int end) {
    std::ifstream src(srcFile, std::ios::binary);
    std::ofstream dest(destFile, std::ios::binary | std::ios::app);
    src.seekg(start);
    int bufferSize = 1024;
    char buffer[bufferSize];
    while (src.tellg() < end && src.read(buffer, bufferSize)) {
        dest.write(buffer, src.gcount());
    }
    src.close();
    dest.close();
}

void copyFile(std::string srcFile, std::string destFile) {
    std::ifstream src(srcFile, std::ios::binary);
    src.seekg(0, src.end);
    int fileSize = src.tellg();
    src.close();

    int numThreads = 2;
    int chunkSize = fileSize / numThreads;

    std::vector<std::thread> threads;
    for (int i = 0; i < numThreads; i++) {
        int start = i * chunkSize;
        int end = (i == numThreads - 1) ? fileSize : start + chunkSize;
        threads.push_back(std::thread(copyFileThread, srcFile, destFile, start, end));
    }

    for (auto& t : threads) {
        t.join();
    }
}

int main() {
    std::string srcFile = "source.txt";
    std::string destFile = "destination.txt";
    copyFile(srcFile, destFile);
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

瞲_大河弯弯

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值