linux 多线程读写文件

本文介绍了一个使用C++实现的Linux多线程文件复制程序。程序通过分配每个线程文件的一部分来提高复制效率,同时处理了文件的打开、关闭、同步等问题,确保正确复制。程序首先获取源文件信息,然后根据线程数量计算每个线程的读取范围,并在各自线程中读取和写入相应部分。最后,所有线程完成后,释放资源并打印完成信息。
摘要由CSDN通过智能技术生成

#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#include <assert.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <pthread.h>
#include<iostream>
#define MAX_PATH 255
#define BLOCK_SIZE 4096

typedef struct
{
    int srcFd; //需要拷贝的文件描述符
    int dstFd; //拷贝后的文件描述符
    int start; //开始标记
    int end_;  //结束标记
} thread_info; //线程信息结构体
/*
函数名: mycopy
函数参数:  源文件路径+名称   目标文件路径+名称  线程数量
函数作用: 1.确立每个线程读取文件的起始点和结束点
         2.确立文件描述符
         3.开辟线程

*/
int mycopy(const char *src, const char *dst, int threads);
void *run(void *arg);      //线程函数

pthread_t *tid = NULL;     //线程id指针
thread_info *tinfo = NULL;  //线程信息结构体指针
pthread_mutex_t mu;
int main(int argc, char *argv[])
{
   /* if (argc != 4)  //判断是否是四个参数(分别是可执行程序 源文件路径+文件名    目标文件路径+文件名  线程数量)
    {
        printf("usage: %s src dst sum_of_thread\n", argv[0]);
        return -1;
    }*/

    char src[MAX_PATH] = {0};    //保存源文件名路径
    char dst[MAX_PATH] = {0};    //保存目标文件路径
    int threads;                 //线程变量

    //memcpy(src, argv[1], strlen(argv[1])); //给源文件路径赋值
    //memcpy(dst, argv[2], strlen(argv[1])); //给目标文件路径赋值

    strcpy(src,"/home/linux/1.mp4");
    strcpy(dst,"/home/linux/2.mp4");

    //threads = atoi(ar

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值