Re: [問題] 求助強者 "r+" 的奇怪現象

看板b98902HW作者 (亨利喵)時間14年前 (2009/12/05 01:50), 編輯推噓1(104)
留言5則, 3人參與, 最新討論串3/3 (看更多)
路人低調路過,想回一下唷! 詳見: http://www.cplusplus.com/reference/clibrary/cstdio/fopen/ 有一段說: For the modes where both read and writing (or appending) are allowed (those which include a "+" sign), the stream should be flushed (fflush) or repositioned (fseek, fsetpos, rewind) between either a reading operation followed by a writing operation or a writing operation followed by a reading operation. 就是你讀/寫切換要fseek一下就是了,詳情為啥我有點忘,想到再跟你講好了XD 好像是buffer問題啦!... Read/Write buffer似乎是共用的之類的事情..... AC的code應該像這樣... #include<stdio.h> int main() { FILE *ptr; int data; ptr=fopen("in.txt","r+"); fscanf(ptr,"%d",&data); fseek(ptr,0,SEEK_CUR); fprintf(ptr,"test"); fprintf(ptr,"%d\n",data); fclose(ptr); return 0; } ※ 引述《barry800414 (小銘)》之銘言: : 本來我是打算讀書會把fopen 的參數都講一下 : 然實際的看有什麼現象發生 : 不過我今天試了好久 : 發現了奇怪的事情... : 自己都爆炸了 XD : #include<stdio.h> : int main() : { : FILE *ptr; : int data; : ptr=fopen("in.txt","r+"); : fscanf(ptr,"%d",&data); : fprintf(ptr,"test"); : fprintf(ptr,"%d\n",data); : fclose(ptr); : return 0; : } : in.txt的內容 : 第一種是只有123456 : 這六個字元 連換行都沒有 : 這個程式可以成功的讓in.txt的內容變成 : 123456test123456 : 第二種是123456這六個字元加一個換行 : 奇怪的事情發生了 : 跑完之後in.txt的內容還是123456 : 連"test" 都沒辦法輸出 : 而我看上課的講義上r+是這麼寫: : Open an existing file for update (reading and writing) : update的定義到底是什麼? : 為什麼上面的程式在第二種狀況會這樣ˊˋ? : 請諸位強者知道的幫忙一下 感激不盡 : 噢我是用devcpp 跑的 附檔名存.c -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.112.90.67 ※ 編輯: scan33scan33 來自: 140.112.90.67 (12/05 01:58)

12/05 02:07, , 1F
感覺還是寫fflush(ptr); 比較有fu XD
12/05 02:07, 1F

12/05 02:13, , 2F
可是fflush(ptr)好像有時會失靈
12/05 02:13, 2F

12/05 02:14, , 3F
對耶!是會失效...我剛剛對這份code試過好像就不行.
12/05 02:14, 3F

12/05 02:15, , 4F
話說dev-C的 FILE header跟工作站上的不一樣.
12/05 02:15, 4F

12/05 02:15, , 5F
所以效果應該是會不一樣.
12/05 02:15, 5F
文章代碼(AID): #1B6Kly6p (b98902HW)
文章代碼(AID): #1B6Kly6p (b98902HW)