text1.txt
begin
10 11 1220 21 22
30 31 32
end
text2.txt
begin
15 16 1725 26 27
35 36 37
end
text3.txt
begin
25 27 2945 47 49
65 67 69
end
手动创建两个文本文件text1.txt,text2.txt,要求编程创建text3.txt,实现text1.txt和text2.txt文件中除去首行和末尾对应的数
据相加,三个文本的内容如上。
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp1;
FILE *fp2;
FILE *fp3;
char c1;
char c2;
char c3;
fp1 = fopen("text1.txt","r"); /*打开文件text1.txt*/
if(NULL == fp1)
{
printf("fopen1 error!\n");
exit(1);
}
fp2 = fopen("text2.txt","r"); /*打开文件text2.txt*/
if(NULL == fp2)
{
printf("fopen2 error!\n");
exit(1);
}
fp3 = fopen("text3.txt","w+"); /*打开文件text3.txt,若文件不存在则创建*/
if(NULL == fp3)
{
printf("fopen3 error!\n");
exit(1);
}
while(((c1 = fgetc(fp1)) != EOF) && ((c2 = fgetc(fp2)) != EOF)) /*若文件text1.txt和文件text2.txt都无字符可 读,则循环结束*/
{
if(((c1>='a'&&c1<='z')&&(c2>='a'&&c2<='z'))||((c1==' ')&&(c2==' '))||((c1 == '\n')&&(c2 == '\n')))
{
c3 = c1;
fputc(c3,fp3); /*向文件text3.txt中写入英文字符,空格字符和换行符*/
}
else
{
c3 = ((c1 -'0') + (c2 - '0')) + '0'; /*将文件text1.txt和text2.txt中的数字字符转换成数字相加,再转化为字符写入text3.txt中*/
fputc(c3,fp3);
}
}
fclose(fp1); /*关闭文件*/
fclose(fp2);
fclose(fp3);
return 0;
}