多线程zuoye

#include <myhead.h>
int getlen(const char *file1, const char *file2)
{
	FILE *fp1 = NULL;
	FILE *fp2 = NULL;
	if((fp1 = fopen(file1, "r")) == NULL)
	{
		perror("file1 fopen error");
		return -1;
	}
	if((fp2 = fopen(file2, "w+")) == NULL)
	{
		perror("file2 fopen error");
		return -1; 
	}
	fseek(fp1, 0, SEEK_END);
	int len = ftell(fp1);
	fclose(fp1);
	fclose(fp2);
	return len;
}
void copy_file(const char *file1, const char *file2, int stat, int len)
{
	FILE *fp1 = NULL;
	FILE *fp2 = NULL;
	if((fp1 = fopen(file1, "r")) == NULL)
	{
		perror("file fopen error");
		return ;
	}
	if((fp2 = fopen(file2, "w")) == NULL)
	{
		perror("file2 fopen error");
		return ;
	}
	fseek(fp1, stat, SEEK_SET);
	fseek(fp2, stat, SEEK_SET);
	char buf[128] = "";
	while(1)
	{
		fread(buf, sizeof(char), 1, fp1);
		int a = ftell(fp1);
		if(a > len)
		{
			break;
		}
		fwrite(buf, sizeof(char), 1, fp2);
		fflush(fp2);
	}
	fclose(fp2);
	fclose(fp1);
	printf("拷贝成功\n");
	return ;
}
typedef struct  
{
	char *src_file;
	char *dst_file;
	int end;
	int mid;
}Data;
void *task1(void *arg)
{
	sleep(5);
	Data data  = (struct Data*)arg;
	copy_file(data.src_file, data.dst_file, data.mid, data.end);
	pthread_exit(NULL);	
}
int main(int argc, const char *argv[])
{
	//向文件写入内容
	FILE *fp = NULL;
	if((fp = fopen("./file1", "w")) == NULL)
	{
		perror("fopen error");
		return -1;
	}
	char buf[128] = "";
	while(1)
	{
		fscanf(stdin, "%s", buf);
		if(strcmp(buf, "nihao") == 0)
		{
			break;
		}
		fprintf(fp, "%s\n", buf);
	}

	//关闭文件刷新
	fclose(fp);
	char src_file[] = "./file1";
	char dst_file[] = "./file2";
	//求源文件的大小
	int len = getlen(src_file,dst_file);
	pthread_t tid;
	int mid = len/2;
	int end = len -len/2;
	Data data = {src_file, dst_file, mid, end};
	if(pthread_create(&tid, NULL, task1, &data))
	{
		printf("线程创建失败\n");
		return -1;
	}
	//主线程拷贝前一半内容

	copy_file(src_file, dst_file, 0, mid);
	//回收子线程
	pthread_join(tid, NULL);
	printf("拷贝成功\n");
	
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值