#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
struct Data
{
int start;
int len;
char *srcfile;
char *dstfile;
};
int getlen(const char* srcfile,const char* dstfile)
{
// 定义两个文件指针
FILE *srcfd;
FILE *dstfd;
// 以只读的方式打开源文件
if((srcfd=fopen(srcfile,"r"))==NULL)
{
perror("fopen error");
return -1;
}
// 以只写的方式打开目标文件
if((dstfd=fopen(dstfile,"w+"))==NULL)
{
perror("fopen error");
return -1;
}
// 求源文件的长度
int len = fseek(srcfd, 0, SEEK_END);
// 关闭文件
fclose(srcfd);
fclose(dstfd);
return len;
}
// 定义拷贝文件函数
void *copy_file(void *arg)
{
struct Data *data = (struct Data*)arg;
// 定义两个文件指针
FILE *srcfd;
FILE *dstfd;
// 以只读的方式打开源文件
if((srcfd=fopen(data->srcfile,"r"))==NULL)
{
perror("fopen error");
return NULL;
}
// 以只写的方式打开目标文件
if((dstfd=fopen(data->dstfile,"w+"))==NULL)
{
perror("fopen error");
return NULL;
}
// 将光标定位到要开始拷贝的位置
fseek(srcfd, data->start, SEEK_CUR);
fseek(dstfd, data->start, SEEK_CUR);
// 开始进行拷贝工作
char buf[128];
while((fread(buf, sizeof(char), sizeof(buf), srcfd))>0)
{
int ret = fread(buf, sizeof(char), sizeof(buf), srcfd);
fwrite(buf, sizeof(char), ret, dstfd);
}
printf("拷贝成功\n");
return;
}
void *copy_file1(void *arg)
{
struct Data *data1 = (struct Data*)arg;
// 定义两个文件指针
FILE *srcfd;
FILE *dstfd;
// 以只读的方式打开源文件
if((srcfd=fopen(data1->srcfile,"r"))==NULL)
{
perror("fopen error");
return NULL;
}
// 以只写的方式打开目标文件
if((dstfd=fopen(data1->dstfile,"w+"))==NULL)
{
perror("fopen error");
return NULL;
}
// 将光标定位到要开始拷贝的位置
fseek(srcfd, data1->start, SEEK_SET);
fseek(dstfd, data1->start, SEEK_SET);
// 开始进行拷贝工作
char buf[128];
while((fread(buf, sizeof(char), sizeof(buf), srcfd))>0)
{
int ret = fread(buf, sizeof(char), sizeof(buf), srcfd);
fwrite(buf, sizeof(char), ret, dstfd);
}
printf("拷贝成功\n");
return;
}int main(int argc, const char *argv[])
{
if(argc != 3)
{
printf("input file error\n");
printf("usage:./a.out srcfile dstfile\n");
return -1;
}
// 求文件的长度
int len = getlen(argv[1], argv[2]);
struct Data data = {len/3,2*len/3, argv[1], argv[2]};
struct Data data1={2*len/3,len,argv[1],argv[2]};
// 定义子线程
pthread_t tid1;
if(pthread_create(&tid1, NULL, copy_file, &data))
{
printf("pthread_create error\n");
return 0;
}
//定义子线程2
pthread_t tid2;
if(pthread_create(&tid2, NULL, copy_file, &data1))
{
printf("pthread_create error\n");
return 0;
}
//调用拷贝函数
copy_file(&data);
sleep(1);
copy_file1(&data1);
// 等待子线程完成拷贝
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
return 0;
}
io进程线程
最新推荐文章于 2024-07-16 09:48:01 发布