文件编程

来源:互联网 发布:cs1.5和1.6知乎 编辑:程序博客网 时间:2024/06/06 11:41

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

text1.txtbegin10 11 1220 21 2230 31 32end text2.txtbegin15 16 1725 26 2735 36 37end text3.txtbegin25 27 2945 47 4965 67 69end
#include <stdio.h>#include <stdlib.h>
int main(){ FILE *text1_fp; FILE *text2_fp; FILE *text3_fp; char ch1; char ch2; char ch3; int temp1; int temp2; int sum;
 if((text1_fp = fopen("text1.txt","r")) == NULL) {  printf("Cannot open file1");  exit(0); }  if((text2_fp = fopen("text2.txt","r")) == NULL) {  printf("Cannot open file2");  exit(0); } if((text3_fp = fopen("text3.txt","w+")) == NULL) {  printf("Cannot open file3");  exit(0); }
 while(((ch1 = fgetc(text1_fp)) !=EOF) && (ch2 = fgetc(text2_fp)) != EOF )  {  if(ch1 < '0' || ch2 > '9')  {   fputc(ch1, text3_fp);  }  else  {   temp1 = ch1 - '0';   temp2 = ch2 - '0';   sum = temp1 + temp2;   ch3 = sum + '0';   fputc(ch3,text3_fp);  } }
 fclose(text1_fp); fclose(text2_fp); fclose(text3_fp);}

0 0