C语言 二进制文件存储读取数据结构的一个疑问
Idea王 2014-03-08 04:23:00 发生如下情况:
使用fread()和frwite()读取
测试情况如下:
1、定义
struct savefile{
bool invb,invbshow,pgrassshow,grasscolor_direct;
player save;
item food,mine[4],Invb,coin,pgrass[4];
float xs[244],ys[244],sizes[244],direct,ttime,SPEED,pgrasscolor,pgrasstime;
int mission,difficulty;
}*savefile=(struct savefile *)malloc(sizeof(struct savefile));
(player,item是自定义数据结构)发现fread到xs后就终止了,也就是float xs[244]之后的所有内容都未读进去,用调试器更改读取前后的各变量值如下:
读取前使用调试器强制更改值:
food.x=-1.000000,xs[0]=-1.000000,ys[0]=-1.000000,sizes[0]=-1.000000,SPEED=-1.000000
读取后:
food.x=7.399999,xs[0]=4.5222222,ys[0]=-1.000000,sizes[0]=-1.000000,SPEED=-1.000000
ys[0]和SPEED值未更改;
确保读取使用方式为"r"且fclose(fp);
2、更改定义
struct savefile{
bool invb,invbshow,pgrassshow,grasscolor_direct;
player save;
item food,mine[4],Invb,coin,pgrass[4];
float xs[244],direct,ys[244],ttime,sizes[244],SPEED,pgrasscolor,pgrasstime;
int mission,difficulty;
}*savefile=(struct savefile *)malloc(sizeof(struct savefile));
调试如下:
读取前使用调试器强制更改值:
food.x=-1.000000,xs[0]=-1.000000,ys[0]=-1.000000,sizes[0]=-1.000000,SPEED=-1.000000
读取后:
food.x=7.399999,xs[0]=4.5222222,ys[0]=3.299999,sizes[0]=0.533333,SPEED=1.1000000
所有值都发生改变
确保使用方式"r"且fclose(fp);
两次文件分别保存,且保存的savefile变量经检查无问题,用fwrite(savefile,1,sizeof(struct savefile,fp)且fclose(fp);
由此得出结论:二进制文件保存不能使用连续的数据结构数组是对的么,为什么会这样。