Re: [問題] feof無窮的問題

看板C_and_CPP (C/C++)作者 (._.?)時間13年前 (2013/03/21 11:31), 編輯推噓1(100)
留言1則, 1人參與, 最新討論串2/2 (看更多)
※ 引述《mnb1234 ()》之銘言: : 開發平台(Platform): (Ex: VC++, GCC, Linux, ...) : ubuntu : 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) : 問題(Question): : 餵入的資料(Input): : 預期的正確結果(Expected Output): : 錯誤結果(Wrong Output): : 在add的函式會變成無窮回圈,不斷的scanf,似乎找不到eof? : 程式碼(Code):(請善用置底文網頁, 記得排版) : main() : { : if ((cptr=fopen("tmp.dat","r+"))==NULL) : printf("Can't open file\n"); : initial(cptr); : add(cptr); : return; : } : void initial(FILE *ptr) : { : int i; : Test test = {"abc","abc","0"}; : rewind(ptr); : for(i=0;i<SIZE;i++){ : fwrite(&test,sizeof(Test),1,ptr); : } : } : void add(FILE *ptr) : { : Test test; : rewind(ptr); : while(!feof(ptr)){ : printf("Input\n"); : scanf("%s%s%s",test.test1,test.test2,test.test3); : fwrite(&test,sizeof(Test),1,ptr); : } : } : 補充說明(Supplement): : 小弟不才,請各位幫忙,謝謝 http://www.cplusplus.com/reference/cstdio/feof/ 先看一下說明 stream 的 end-of-File indicator 被設定 通常是因為對這個 stream 嘗試讀取 eof 位置或是 eof 位置以後的資料 接下來看文中的 add function rewind(ptr); http://www.cplusplus.com/reference/cstdio/rewind/ 這個步驟是將 ptr 移回檔案開頭, eof indicator 也會被重設 意思是說, 執行這個 function 之後 feof(ptr) 必定是 false 前面有提到 eof indicator 會在該 stream 嘗試讀取 eof 位置 或是 eof 以後的資料被設定 接下來再來看看你 while loop 當中的內容 什麼情況 eof indicator 會被設定 1. printf 這個是對 stdin 的處理, 與 ptr 相關的 stream 無關 2. scanf 同 1. 3. fwrite 這個是寫入的指令, 不會影響 eof indicator 所以我們可以得到結論 無論檔案內容是什麼, feof(ptr) 在這段 code 中永遠都是 false 所以 while loop 就會一直跑下去 --- 補充一下 有寫 fopen 沒寫對應的 fclose 會遭天譴喔.. -- 有沒有想要補充或發問的 ._./ ? -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.116.72.59 ※ 編輯: pcyu16 來自: 140.116.72.59 (03/21 11:33)

03/21 14:53, , 1F
感謝,我對eof的想法錯誤了,感謝高手的糾正!!!!
03/21 14:53, 1F
文章代碼(AID): #1HIdy2YM (C_and_CPP)
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 2 之 2 篇):
文章代碼(AID): #1HIdy2YM (C_and_CPP)