周末作业。

该代码示例展示了两个多线程程序,分别用于读取和写入文件。第一个线程从源文件中读取内容并追加到目标文件,第二个线程将源文件内容逆序写入目标文件。程序使用了`open`、`lseek`、`read`和`write`等系统调用,并通过`pthread_create`创建线程。
摘要由CSDN通过智能技术生成

在这里插入图片描述

#include <stdio.h>
#include <sys/stat.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <pthread.h>
#include <string.h>
#include <fcntl.h>
char str[20]="";
ssize_t a;
ssize_t b;
off_t c;
off_t p;
off_t j;
int fd;
void *ptr(void *fz){

	//sleep(3);
	fd=open("./copy5.jpg",O_RDWR|O_CREAT|O_APPEND,0777);
	if(0==fd){
		perror("open");
		return 0;
	}
	c=lseek(*(int*)fz,0,SEEK_END);
	lseek(*(int*)fz,0,SEEK_SET);
	j=c/2;
	while(1){
		p=j/sizeof(str)==0?j:sizeof(str);


		if((a=read(*(int*)fz,str,sizeof(str)))== -1){
			perror("read");
			return 0;
		}
		if(a==0){
			break;
		}
		if((b=write(fd,str,p))== -1){
			perror("write");
			return 0;
		}
		if((j -= sizeof(str))<0){
			break;
		}
	}
}

void *sar(void *dy){

	sleep(3);
	fd=open("./copy5.jpg",O_RDWR|O_CREAT|O_APPEND,0777);
	if(0==fd){
		perror("open");
		return 0;
	}

	c=lseek(*(int*)dy,0,SEEK_END);
	int falg=0;

		if(c%2!=0){
		falg=1;
	}

	j=c/2+falg;
	printf("%ld\n",j);
	lseek(*(int*)dy,j,SEEK_SET);
	while(1){
		p=j/sizeof(str)==0?j:sizeof(str);
		if((a=read(*(int*)dy,str,p))== -1){
			perror("read");
			return 0;
		}
		if(a==0){
			break;
		}
		if((b=write(fd,str,p))== -1){
			perror("write");
			return 0;
		}
		if((j -= sizeof(str))<0){
			break;
		}
	}
}


int main(int argc, const char *argv[])
{
	if(argc<2){
		printf("请输入要拷贝的图片名\n");	
		return 0;
	}

	int fg=open(argv[1],O_RDONLY);
	if(0==fg){
		perror("open");
		return 0;
	}

	pthread_t tid;
	if(pthread_create(&tid,NULL,ptr,(void*)&fg)!=0){
		perror("pthread_create");
		return 0;
	}


	pthread_t aid;
	if(pthread_create(&aid,NULL,sar,(void*)&fg)!=0){
		perror("pthread_create");
		return 0;
	}



	while(1){
		sleep(1);
	}


	return 0;
}

`作业1 逆置``
在这里插#include <stdio.h>
#include <sys/stat.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <pthread.h>
#include <string.h>

int c=10;
char str[]=“123456”;
int falg=0;
void *ptr(void *fz){
while(1){
sleep(1);
char *start=str;
int len=strlen(str);
char *end=(str+len-1);
char temp=0;
while(start < end){
temp = *start;
*start = *end;
*end=temp;
start++;
end–;
falg=1;
}
}
}

void *sar(void *dy){
while(1){
sleep(1);
if(falg==1)
printf(“%s\n” ,str);
}
}
int main(int argc, const char *argv[])
{
pthread_t tid;
if(pthread_create(&tid,NULL,ptr,NULL)!=0){
perror(“pthread_create”);
return 0;
}

pthread_t aid;
if(pthread_create(&aid,NULL,sar,NULL)!=0){
	perror("pthread_create");
	return 0;
}else{

	while(1){
		sleep(1);
	}
}



return 0;

}
入代码片


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值