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