IO 多线程拷贝图片

1. 要求创建两个线程,以及一个全局变量,char str[] = "123456";要求如下:

1)一个线程专门用于打印str;

2)另外一个线程专门用于倒置str字符串,不使用辅助数组。

#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
char str[] = "123456";
void* callback(void* arg)
{
	char* star = str;
	char* end = str;
	while(*end!='\0'){
		end++;
	}
	end--;
	while(end>star){
		*star ^= *end;
		*end ^= *star;
		*star ^= *end;
		end--;
		star++;
	}
}


int main(int argc, const char *argv[])
{
	pthread_t tid;
	if(pthread_create(&tid,NULL,callback,NULL)!=0)
	{
		perror("pthread");
	}
	sleep(1);
	printf("%s\n",str);
	return 0;
}

2. 要求用线程拷贝一张图片,一个线程拷贝前半部分,另一个线程拷贝后半部

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <pthread.h>
int f1 = 0;
int f2 = 0;
void* callback(void* arg)
{
	FILE* fp;
	FILE* fn;
	fp = fopen((char*)arg,"r");
	if(fp<0){
		perror("open3");
		return NULL;
	}
	fn = fopen("zyl.png","a+");
	if(fn<0){
		perror("open4");
		return NULL;	
	}	
	long num = fseek(fp,0,SEEK_END);
	num = ftell(fp);
	fseek(fp,num/2,SEEK_SET);
	fseek(fn,num/2,SEEK_SET);
	char arr[1000] ="";
	size_t res;
	while((res = fread(arr,1,sizeof(arr),fp))!=0){
		fwrite(arr,res,1,fn);
		bzero(arr,res);
	}
	printf("后半部分拷贝完毕!\n");
	f2 = 1;
	fclose(fp);
	fclose(fn);
}
int main(int argc, const char *argv[])
{
	FILE* fp;
	FILE* fn;
	fp = fopen(argv[1],"r");
	if(fp<0){
		perror("open1");
		return -1;
	}
	fn = fopen("zyl.png","w");
	if(fn<0){
		perror("open2");
		return -1;	
	}
	fseek(fp,0,SEEK_END);
	long num = ftell(fp);
	pthread_t tid;
	if(pthread_create(&tid,NULL,callback,(void*)argv[1])!=0){
		perror("pthread");
	}
	fseek(fp,0,SEEK_SET);
	fseek(fn,0,SEEK_SET);
	char a ='0';
	for(int i=0;i<num/2;i++){
		fread(&a,1,1,fp);
		fwrite(&a,1,1,fn);
	}
	printf("前半段拷贝完毕!\n");
	f1 = 1;
	fclose(fp);
	fclose(fn);
	sleep(1);
//	while(!(f1&&f2));
	return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值