日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

手动创建两个文本文件text1.txt和text2.txt,按要求创建text3.txt

發布時間:2023/12/19 编程问答 19 豆豆
生活随笔 收集整理的這篇文章主要介紹了 手动创建两个文本文件text1.txt和text2.txt,按要求创建text3.txt 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

實現在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; // 讀取分辨12中的數據,相加存入3while (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; }

總結

以上是生活随笔為你收集整理的手动创建两个文本文件text1.txt和text2.txt,按要求创建text3.txt的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。