手动创建两个文本文件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; }