实现在text1.txt和text2.txt文件中除去首行和末尾对应的数据,要求三个文本内容如下:
text1 text2 text3
begin begin begin
10 11 12 15 16 17 25 27 29
20 21 22 25 26 27 45 47 49
30 31 32 35 36 37 65 67 69
end end end
这个程序需要用到fopen()函数,fgetc()和fputc()函数,对text1和text2需要只读"r+",而text3需要创建并写入"w+",当检测到text1中是数字时,就可以将text1和text2中的内容相加,在text1,text2和text3中分别定义一个char型,ch1,ch2,ch3,在赋值时要注意赋值语句是ch3=ch1+ch2-'0',因为ch1和ch2都是字符直接相加并不能得到相应的结果,要减去一个字符‘0’。具体源程序如下:
#include <stdio.h>
#include <string.h>
int main()
{
FILE *text1 = fopen("text1.txt", "r+");
if (text1 == NULL)
{
perror("fopen text1.txt");
return 0;
}
FILE *text2 = fopen("text2.txt", "r+");
if (text2 == NULL)
{
perror("fopen text2.txt");
return 0;
}
FILE *text3 = fopen("text3.txt", "w+");
if (text3 == NULL)
{
perror("fopen text3.txt");
return 0;
}
char ch1;
char ch2;
char ch3;
while (1)
{
ch1 = fgetc(text1);
if (ch1 == EOF)
{
break;
}
ch2 = fgetc(text2);
if (ch2 == EOF)
{
break;
}
if (ch1 >= '0' && ch1 <= '9')
{
ch3 = ch1 + ch2 - '0';
fputc(ch3,text3);
}
else if(fputc(ch1, text3) == EOF)
{
perror("fputc");
break;
}
}
fclose(text1);
fclose(text2);
fclose(text3);
return 0;
}