看板 ESOE-90 關於我們 聯絡資訊
關於檔案讀寫的部份... 把下面的寫法背起來. 自己會寫當然最好, 因為下面多少有點取巧. 記得把 "tmpfile1", "tmpfile2" 改成你要的檔名. 三種作法幾乎是一模一樣. 但是套 [2] 的時候特別注意一下, 用 ^Z(ctrl-Z) 結束鍵盤輸入. 千萬不要用 ^C(ctrl-C). (別擔心, 這個是一種小程式的標準寫法... ) ------------------------------------------------------------ [1] 從檔案讀, 寫入檔案... ------------------------------------------------------------ # include <stdio.h> # include <stdlib.h> int main() { FILE *fp1, *fp2; fp1 = fopen("tmpfile1", "r"); fp2 = fopen("tmpfile2", "w"); if (fp1 == NULL || fp2 == NULL) exit(1); while (!feof(fp1)) { if (fscanf(fp1, "", ...) == 0) /* 改參數 */ continue; /******************************************* * * * 要做什麼都寫在這裡... * * * *******************************************/ fprintf(fp2, "", ...); /* 改參數 */ } fclose(fp1), fclose(fp2); return 0; } ------------------------------------------------------------ [2] 從鍵盤讀, 寫入檔案. 與 [1] 有一行不同. ^Z 結束鍵盤輸入. ------------------------------------------------------------ # include <stdio.h> # include <stdlib.h> int main() { FILE *fp1, *fp2; fp1 = stdin; /* 與 [1] 的相異處. */ fp2 = fopen("tmpfile2", "w"); if (fp1 == NULL || fp2 == NULL) exit(1); while (!feof(fp1)) { if (fscanf(fp1, "", ...) == 0) /* 改參數 */ continue; /******************************************* * * * 要做什麼都寫在這裡... * * * *******************************************/ fprintf(fp2, "", ...); /* 改參數 */ } fclose(fp1), fclose(fp2); return 0; } ------------------------------------------------------------ [3] 從檔案讀, 輸出至螢幕. 與 [1] 有一行不同. ------------------------------------------------------------ # include <stdio.h> # include <stdlib.h> int main() { FILE *fp1, *fp2; fp1 = fopen("tmpfile1", "r"); fp2 = stdout; /* 與 [1] 的相異處. */ if (fp1 == NULL || fp2 == NULL) exit(1); while (!feof(fp1)) { if (fscanf(fp1, "", ...) == 0) /* 改參數 */ continue; /******************************************* * * * 要做什麼都寫在這裡... * * * *******************************************/ fprintf(fp2, "", ...); /* 改參數 */ } fclose(fp1), fclose(fp2); return 0; } ------------------------------------------------------------ 這樣應該可以應付考試... -- 新詩練習:新鮮。踩破初春裡的狗大便;不經意的滄桑,滿溢著嫩黃的喜悅。 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 61.224.161.23