文本内容相加

手动创建两个文本文件text1.txt,text2.txt,要求编程创建text3.txt,实现text1.txt和text2.txt文件中除去首行和末尾对应的数据相加,三个文本的内容如下


linux下 用write 和read实现




#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main()
{
int fd1=open("1.txt",O_RDONLY);
if(fd1==-1)
{
printf("fd1 open error\n");
return -1;
}
int fd2=open("2.txt",O_RDONLY);
if(fd2==-1)
{
printf("fd2 open error\n");
return -1;
}


int fd3=open("3.txt",O_WRONLY|O_CREAT);
if(fd3==-1)
{
printf("fd3 open error\n");
return -1;
}


char ch[]="begin\r\n";
write(fd3,ch,strlen(ch));




char ch1,ch2,ch3[20];
int i,q=0;

while(ch1!='\n')
{
read(fd1,&ch1,1);

}
while(ch2!='\n')
{
read(fd2,&ch2,1);

}
read(fd1,&ch1,1);
read(fd2,&ch2,1);
while(ch1!='e')
{


int s=0,k=10,s2=0;


while(ch1!=' '&&ch1!='\r')
{
s=s*k+ch1-48;
s2=s2*k+ch2-48;
read(fd1,&ch1,1);
read(fd2,&ch2,1);
}
q++;


if(ch1=='\r')
{
read(fd1,&ch1,1);
read(fd2,&ch2,1);
}


sprintf(ch3,"%d ",s+s2);
write(fd3,ch3,strlen(ch3));
if(q%3==0)
{
q=0;
write(fd3,"\r\n",2);
}
printf("%d,%d\n",s,s2);




read(fd1,&ch1,1);
read(fd2,&ch2,1);




}


write(fd3,"end",3);
close(fd1);
close(fd2);
close(fd3);
return 0;
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值