實現在text1.txt和text2.txt文件中除去首行和末尾對應的數據,要求三個文本內容如下:
text1 text2 text3begin begin begin10 11 12 15 16 17 25 27 2920 21 22 25 26 27 45 47 4930 31 32 35 36 37 65 67 69end end end
這個程序需要用到fopen()函數,對text1和text2需要只讀”r+”,而text3需要創建并寫入”w+”,當檢測到text1中是數字時,就可以將text1和text2中的內容相加,在text1,text2和text3中分別定義一個char型,ch1,ch2,ch3,在賦值時要注意賦值語句是ch3=ch1+ch2-‘0’,因為ch1和ch2都是字符直接相加并不能得到相應的結果,要減去一個字符‘0’。
第一種用fgetc()和fputc()函數 具體源程序如下:
#include <stdio.h>
#include <string.h> // 函數功能:打開文件
FILE* Fopen (const char *path, const char *mode)
{FILE* fp = fopen (path, mode);if (NULL == fp){perror ("fopen path");return;}return fp;
} int main()
{
// 不調用函數
/*************************************************************FILE *fp1= fopen("text1.txt", "r+"); if (text1 == NULL) { perror("fopen text1.txt"); return 0; } FILE *fp2 = fopen("text2.txt", "r+"); if (text2 == NULL) { perror("fopen text2.txt"); return 0; } FILE *fp3= fopen("text3.txt", "w+"); if (text3 == NULL) { perror("fopen text3.txt"); return 0; }
***********************************************************/FILE *fp1= Fopen ("text1.txt", "r+");FILE *fp2= Fopen ("text2.txt", "r+");FILE *fp3= Fopen ("text3.txt", "w+");char ch1; char ch2; char ch3; // 讀取分辨1和2中的數據,相加存入3中while (1) { ch1 = fgetc(fp1); if (ch1 == EOF) { break; } ch2 = fgetc(fp2); if (ch2 == EOF) { break; } if (ch1 >= '0' && ch1 <= '9') // 判 斷是否是數字{ ch3 = ch1 + ch2 - '0'; fputc(ch3,fp3); } else if(fputc(ch1, fp3) == EOF) // 不是則直接寫入3中 { perror("fputc"); break; } } fclose(fp1); fclose(fp2); fclose(fp3); return 0;
}
下面是不用fgetc()和fputc()函數的寫法 具體源程序如下:
#include <stdio.h>#define SIZE 10// 函數功能:打開文件
FILE* Fopen (const char *path, const char *mode)
{FILE* fp = fopen (path, mode);if (NULL == fp){perror ("fopen path");return;}return fp;
} int main()
{FILE *fp1 = Fopen ("text1.txt", "r+");FILE *fp2 = Fopen ("text2.txt", "r+");FILE *fp3 = Fopen ("text3.txt", "w+");int ret1;int ret2;char buf1[SIZE] = {0};char buf2[SIZE] = {0};// 讀取并分辨1和2中的數據,相加存入3中,結束標志為2中數據讀完while(ret1 = fread (buf1, sizeof(char), 1, fp1)){ ret2 = fread (buf2, sizeof(char), 1, fp2);// 退出循環條件:1或2讀完if(ret2 == 0 && !feof(fp2)){perror("fread");return -1;}if(ret1 == 0 && !feof(fp1)){perror("fread");return -1;}// 判斷是否是數字,是則進行運算,不是則直接導入3if(buf1[0] >= '0' && buf1[0] <= '9'){char tmp[1] = {0};tmp[0] = buf1[0] + buf2[0] - '0';fwrite(tmp, sizeof(char), 1, fp3);}else{fwrite(buf1,sizeof(char),1,fp3);}}close(fp1);close(fp2);close(fp3);return 0;
}