Reputation: 341
I've been trying to write a binary file with some information in a program but I can't make it work. I write it and try to read it to see if it worked. This is the struct I'm trying to write inside the file:
typedef struct{
int puntuacio;
int posicio_x;
int posicio_y;
int vides;
int direccio;
}Jugador;
I've got a variable called player
of type Jugador
. In the function I work with the binary file I recieve player
as a pointer (so Jugador *player
). This is the code I've written (I only give the relevant parts):
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
prints the name correctly but I get an additional garbage character in the last position of the string, but that's easy to solve. auxint
prints perfect. But I get what I guess are memory adresses when I print the parameters of auxjug
.
Upvotes: 1
Views: 798
Reputation: 4767
fwrite(&player,sizeof(Jugador*),1,f);
is only writing a pointer size element (4 or 8 bytes) to the file. You need to have:
fwrite(player,sizeof(Jugador),1,f);
without the extra &
and the extra *
.
Another problem is that you only output strlen(nom)
bytes to the file. But when you read the file, you read exactly 20 bytes. So you should probably pad your nom
string to 20 bytes and fwrite exactly 20 bytes to the file:
fwrite(nom,sizeof(char),20,f);
...
fread(auxp,sizeof(char),20,f);
Upvotes: 4