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

作者: lj0113 (tiny legend)   2015-06-25 21:19:11
開發平台(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 目前指到檔案哪裡嗎 ?
作者: dearsophia (今天真熱)   2015-06-25 21:39:00
wb只能寫,不能讀,要用wb+
作者: kdjf (我抓得到什麼呢?)   2015-06-25 22:01:00
ftell()/fgetpos()arg是FILE*

Links booklink

Contact Us: admin [ a t ] ucptt.com