[問題] fread & printf 程式的蟲除不太掉

看板C_and_CPP (C/C++)作者 (tiny legend)時間10年前 (2015/06/25 21:19), 10年前編輯推噓1(102)
留言3則, 2人參與, 最新討論串1/1
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) Code Blocks 問題(Question): 目前在練習檔案處理, 開檔案是 fopen( "wb" ) binary mode, 在使用 fread 讀值時, 發覺一直 print 不出來 錯誤結果(Wrong Output): 是亂碼 程式碼(Code):(請善用置底文網頁, 記得排版) #include <stdio.h> #include <stdlib.h> #include <string.h> struct person{ char lastName[ 15 ]; char firstName[ 15 ]; char age[ 4 ]; }; int main() { struct person blank = { "unassigned", "", "0" }; struct person hold; FILE * infoFPtr; if( (infoFPtr = fopen( "nameage.dat", "wb" )) == NULL ) printf( "Failed to open file\n" ); else fwrite( &blank, sizeof( struct person ), 1, infoFPtr ); //_ (a) // fclose( infoFPtr ); // if( (infoFPtr = fopen( "nameage.dat", "rb" )) == NULL ) // printf( "Failed to open file\n" ); // else //_ (b) // rewind( infoFPtr ); fread( &hold, sizeof( struct person ), 1, infoFPtr ); printf( "%15s%15s%4s\n", hold.lastName, hold.firstName, hold.age ); fclose( infoFPtr ); return 0; } 補充說明(Supplement): 當使用 (a) 時, comment (b). 檔案內容 correct. console correct. 當使用 (b) 時, comment (a). 檔案內容 correct. console incorrect( 亂碼 ). 有一版程式改到比較長, 讓 program 去 run 時, 有正常, 但 debug 其他東西時. 就變這樣了, 蟲除到有點桑心 O_Q 想順便請問, 假設有一個 FILE * ptr, 有辦法知道這個 ptr 目前指到檔案哪裡嗎 ? -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 1.173.16.21 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1435238354.A.EFC.html

06/25 21:39, , 1F
wb只能寫,不能讀,要用wb+
06/25 21:39, 1F
D大, correct. +是 update ( for both input and output ). 看來 function def 還不夠熟 Thanks :)

06/25 22:01, , 2F
ftell()/fgetpos()
06/25 22:01, 2F

06/25 22:01, , 3F
arg是FILE*
06/25 22:01, 3F
K大, 這個我沒用過. 但看 fseek 裡面有提到 ftell, 我會研究下滴 thx! ※ 編輯: lj0113 (1.173.16.21), 06/25/2015 22:23:53
文章代碼(AID): #1LY__Ixy (C_and_CPP)
文章代碼(AID): #1LY__Ixy (C_and_CPP)