一个数一个数加
/*****************************************************
copyright (C), 2014-2015, Lighting Studio. Co., Ltd.
File name:
Author:Jerey_Jobs Version:0.1 Date:
Description:
Funcion List:
*****************************************************/
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *text1_fp;//FILE是库函数,不是系统调用
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)//以只读的方式打开 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);//所有运算都没有进位,如10 15 他是1+1,0+5,形成25
}
}
fclose(text1_fp);
fclose(text2_fp);
fclose(text3_fp);
return 0;
}
两个数加
/*****************************************************
copyright (C), 2014-2015, Lighting Studio. Co., Ltd.
File name:
Author:Jerey_Jobs Version:0.1 Date:
Description:
Funcion List:
*****************************************************/
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *text1_fp;//FILE是库函数,不是系统调用
FILE *text2_fp;
FILE *text33_fp;
char ch1;
char ch2;
char ch3;
char ch4;
int temp1 = 0;
int temp2 = 0;
int sum;
if((text1_fp = fopen("text1.txt","r")) == NULL)//以只读的方式打开 NULL是做错误处理
{
printf("Cannot open file1");
exit(0);
}
if((text2_fp = fopen("text2.txt","r")) == NULL)
{
printf("Cannot open file2");
exit(0);
}
if((text33_fp = fopen("text33.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')//要判断是begin后面的回车,还是数字后面的空格或回车
{
// fputc(ch1,text3_fp);//非数字字符直接写
sum = temp1 + temp2;//sum为0
if(sum != 0)//只要取了数字就一定不是0
{
ch3 = sum/10 + '0';//十位
ch4 = sum%10 + '0';//个位
fputc(ch3,text33_fp);//先写十位,再写个位
fputc(ch4,text33_fp);
}
fputc(ch1,text33_fp);//如果是字母就直接输出
temp1 = 0;
temp2 = 0;
}
else//数字字符
{
/* temp1 = ch1 -'0';//数字字符转换成对应的数字
temp2 = ch2 -'0';
sum = temp1 + temp2;
ch3 = sum + '0';//加完也不能直接写,要转换成对应的数字字符
fputc(ch3,text33_fp);//所有运算都没有进位,如10 15 他是1+1,0+5,形成25
*/
temp1 = temp1 * 10 + ch1 - '0';//第一个文件
temp2 = temp2 * 10 + ch2 - '0';//第二个文件
}
}
fclose(text1_fp);
fclose(text2_fp);
fclose(text33_fp);
return 0;
}