(C語言)手動創建兩個文本文件text1.txt,text2.txt,要求編程創建text3.txt,實現text1.txt和text2.txt文件中除去首行和末尾對應的數據相加,三個文本的內容如上

在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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章