【发布时间】:2015-05-13 22:48:29
【问题描述】:
我一直在尝试在程序中编写包含一些信息的二进制文件,但我无法使其工作。我写了它并尝试阅读它以查看它是否有效。这是我试图在文件中写入的结构:
typedef struct{
int puntuacio;
int posicio_x;
int posicio_y;
int vides;
int direccio;
}Jugador;
我有一个名为player 的变量,类型为Jugador。在函数中,我使用二进制文件接收player 作为指针(所以Jugador *player)。这是我写的代码(我只给出相关部分):
f=fopen("whatever.bin","wb+");
fwrite(nom,sizeof(char),strlen(nom),f); //nom is a string containing the player's name
fwrite(&player,sizeof(Jugador*),1,f);
auxint=player->direccio; //just doing this to see if I pass the info correctly
fwrite(&auxint,sizeof(int),1,f);
//auxp, auxjug and auxint are auxiliar variables I declared inside the function
fseek(f,0,SEEK_SET); //go to the start of the file before reading
fread(auxp,sizeof(char),20,f);
fread(&auxjug,sizeof(Jugador),1,f);
fread(&auxint,sizeof(int),1,f);
printf("auxp:%s--\n",auxp);
printf("puntuacio:%d--\n",auxjug.puntuacio);
printf("dir:%d--\n",auxjug.direccio);
printf("posx:%d--\n",auxjug.posicio_x);
printf("posy:%d--\n",auxjug.posicio_y);
printf("vids:%d--\n",auxjug.vides);
printf("auxint:%d--",auxint);
auxp 正确打印了名称,但我在字符串的最后一个位置得到了一个额外的垃圾字符,但这很容易解决。 auxint 打印完美。但是当我打印auxjug 的参数时,我猜到了内存地址。
【问题讨论】:
标签: c pointers binaryfiles fwrite fread