作者lj0113 (tiny legend)
看板C_and_CPP
標題[問題] fread & printf 程式的蟲除不太掉
時間Thu Jun 25 21:19:11 2015
開發平台(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
推 dearsophia: wb只能寫,不能讀,要用wb+ 06/25 21:39
D大, correct. +是 update ( for both input and output ).
看來 function def 還不夠熟 Thanks :)
→ kdjf: ftell()/fgetpos() 06/25 22:01
→ kdjf: arg是FILE* 06/25 22:01
K大, 這個我沒用過. 但看 fseek 裡面有提到 ftell, 我會研究下滴 thx!
※ 編輯: lj0113 (1.173.16.21), 06/25/2015 22:23:53