手动创建两个文本文件text1.txt和text2.txt,按要求创建text3.txt

     实现在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;
}


  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值