[问题] 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