在APUE上面看到了标准IO库,就正好回忆起一个面试题,就贴一下在博客里
首先分析一下:在test1.txt,和test2.txt中只要是字母的都没有改变,原封不动的放在test3.txt中。是数字的都加在一起,放在test3.txt中。
#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>
//是"数字"的判断
int isNum(char ch)
{
if(ch >= '0' && ch <= '9')
{
return 1;
}
else
{
return 0;
}
}
int main()
{
//以读的方式打开文件
FILE * fp1 = fopen("test1.txt","r");
if(fp1 == NULL)
{
perror("fopen1 error");
exit(-1);
}
//以读的方式打开文件
FILE * fp2 = fopen("test2.txt","r");
if(fp2 == NULL)
{
perror("fopen2 error");
exit(-1);
}
//以写的方式打开文件
FILE * fp3 = fopen("test3.txt","w");
if(fp3 == NULL)
{
perror("fopen3 error");
exit(-1);
}
//初始化3个字符
char ch1 = '0';
char ch2 = '0';
char ch3 = '0';
while((ch1 = getc(fp1)) != EOF && (ch2 = getc(fp2)) != EOF)
{
//注意这边:是用字符去读取,要先转成数字,再进行"+"运算,之后再转成字符存入到test3.txt.
if(isNum(ch1) && isNum(ch2))
{
ch1 = ch1 - '0';
ch2 = ch2 - '0';
ch3 = ch1 + ch2;
ch3 = ch3 + '0';
putc(ch3,fp3);
}
//只要不是"字符",就照样输出
else
{
ch3 = ch1;
putc(ch3,fp3);
}
}
//关闭文件1,2,3
fclose(fp1);
fclose(fp2);
fclose(fp3);
return 0;
}