实现在text1.txt和text2.txt文件中除去首行和末尾对应的数据,要求三个文本内容如下:
text1 text2 text3begin begin begin10 11 12 15 16 17 25 27 2920 21 22 25 26 27 45 47 4930 31 32 35 36 37 65 67 69end end end
这个程序需要用到fopen()函数,对text1和text2需要只读”r+”,而text3需要创建并写入”w+”,当检测到text1中是数字时,就可以将text1和text2中的内容相加,在text1,text2和text3中分别定义一个char型,ch1,ch2,ch3,在赋值时要注意赋值语句是ch3=ch1+ch2-‘0’,因为ch1和ch2都是字符直接相加并不能得到相应的结果,要减去一个字符‘0’。
第一种用fgetc()和fputc()函数 具体源程序如下:
#include <stdio.h>
#include <string.h> // 函数功能:打开文件
FILE* Fopen (const char *path, const char *mode)
{FILE* fp = fopen (path, mode);if (NULL == fp){perror ("fopen path");return;}return fp;
} int main()
{
// 不调用函数
/*************************************************************FILE *fp1= fopen("text1.txt", "r+"); if (text1 == NULL) { perror("fopen text1.txt"); return 0; } FILE *fp2 = fopen("text2.txt", "r+"); if (text2 == NULL) { perror("fopen text2.txt"); return 0; } FILE *fp3= fopen("text3.txt", "w+"); if (text3 == NULL) { perror("fopen text3.txt"); return 0; }
***********************************************************/FILE *fp1= Fopen ("text1.txt", "r+");FILE *fp2= Fopen ("text2.txt", "r+");FILE *fp3= Fopen ("text3.txt", "w+");char ch1; char ch2; char ch3; // 读取分辨1和2中的数据,相加存入3中while (1) { ch1 = fgetc(fp1); if (ch1 == EOF) { break; } ch2 = fgetc(fp2); if (ch2 == EOF) { break; } if (ch1 >= '0' && ch1 <= '9') // 判 断是否是数字{ ch3 = ch1 + ch2 - '0'; fputc(ch3,fp3); } else if(fputc(ch1, fp3) == EOF) // 不是则直接写入3中 { perror("fputc"); break; } } fclose(fp1); fclose(fp2); fclose(fp3); return 0;
}
下面是不用fgetc()和fputc()函数的写法 具体源程序如下:
#include <stdio.h>#define SIZE 10// 函数功能:打开文件
FILE* Fopen (const char *path, const char *mode)
{FILE* fp = fopen (path, mode);if (NULL == fp){perror ("fopen path");return;}return fp;
} int main()
{FILE *fp1 = Fopen ("text1.txt", "r+");FILE *fp2 = Fopen ("text2.txt", "r+");FILE *fp3 = Fopen ("text3.txt", "w+");int ret1;int ret2;char buf1[SIZE] = {0};char buf2[SIZE] = {0};// 读取并分辨1和2中的数据,相加存入3中,结束标志为2中数据读完while(ret1 = fread (buf1, sizeof(char), 1, fp1)){ ret2 = fread (buf2, sizeof(char), 1, fp2);// 退出循环条件:1或2读完if(ret2 == 0 && !feof(fp2)){perror("fread");return -1;}if(ret1 == 0 && !feof(fp1)){perror("fread");return -1;}// 判断是否是数字,是则进行运算,不是则直接导入3if(buf1[0] >= '0' && buf1[0] <= '9'){char tmp[1] = {0};tmp[0] = buf1[0] + buf2[0] - '0';fwrite(tmp, sizeof(char), 1, fp3);}else{fwrite(buf1,sizeof(char),1,fp3);}}close(fp1);close(fp2);close(fp3);return 0;
}