jcxc day2

#include <myhead.h>

#include <pthread.h>

//结构体描述,把好多个变量传给这个拷贝子进程

struct Info

{  

 //四个数据分别是:源文件,目标文件,光标位置,拷贝大小

 //俩个线程共用一个线程体,二者的区别就在于光标和拷贝大小

 char *s;

 char *d;

 int start;

 int size;

};

/*

 * function: 求文件长度

 * @param [ in] 源文件,目标文件

 * @param [out] 

 * @return 文件长度

 */

int file_len ( const char *sf , const char *df )

{  

 //定义俩个文件描述符

 int sfd;

 int dfd;

 //先打开源文件,并创建和清空目标文件

 if ( (sfd = open ( sf , O_RDONLY )) == -1 )

 {

  printf ( "打开失败" );

  return -1;

 }

 if ( (dfd = open ( df , O_RDONLY|O_CREAT|O_TRUNC , 0664 )) == -1 )

 {

  printf ( "打开失败" );

  return -1;

 }

 //计算长度

 int len = lseek ( sfd , 0 , SEEK_END );

 //关闭俩个文件

 close ( sfd );

 close ( dfd );

 return len;

}

//定义线程体,把copy的功能就封装在线程体里

void *copy ( void *info )

{

 //定义俩个文件描述符

 int sfd;

 int dfd;

 //强转

 struct Info data;

 data = *(struct Info *)info;

 //打开源文件和目标文件

 if ( (sfd = open ( data.s , O_RDONLY )) == -1 )

 {

  perror ( "" );

  return NULL;

 }

 if ( (dfd = open ( data.d , O_WRONLY )) == -1 )

 {

  perror ( "" );

  return NULL;

 }

 //定义瓢

 char buf[32] = "";

 //先移动俩个文件的光标

 lseek ( sfd , data.start , SEEK_SET );

 lseek ( dfd , data.start , SEEK_SET );

 //读源文件,写入目标文件,完成拷贝

 int count = 0;

 while ( 1 )

 {

  int ret = read ( sfd , buf , sizeof(buf) );

  count += ret;

  if (ret == 0 || count >= data.size )

  {  

   write ( dfd , buf , ret - (count - data.size) );

   break;

  }

  write ( dfd , buf , ret );

 }

}

int main(int argc, const char *argv[])

{  

 //判断

 if ( argc != 3 )

 {

  printf ( "少参数" );

  return -1;

 }

 //搞个函数去求出源文件的大小,并且创建清空目标文件

 int len = file_len ( argv[1] , argv[2] );

 //创建变量去保存线程号

 pthread_t tid1;

 pthread_t tid2;

 //定义俩个结构体变量,并初始化

 struct Info first = { argv[1] , argv[2] , 0 , len/2 };

 struct Info second = { argv[1] , argv[2] , len/2 , len-(len/2) };

 //用函数创建俩个线程

 if ( pthread_create (&tid1 , NULL , copy , &first) )

 {

  perror ( "" );

  return -1;

 }

 if ( pthread_create (&tid2 , NULL , copy , &second) )

 {

  perror ( "" );

  return -1;

 }

 while ( 1 );

 return 0;

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值