#include <stdio.h>
typedef struct Forca // definining struct here
{
char palavra[TAM_PALAVRA];
char palavra_mascarada[TAM_PALAVRA];
int erros, acertos, tentativas;
} t_forca;
void salva_jogo(t_forca forca) //function that writes structure inside bin file
{
FILE* save;
save = fopen("save.bin", "w b");
if (save == NULL)
{
printf("\nerro no arquivo\n");
}
fwrite(&forca, sizeof(forca), 1, save);
fclose(save);
}
void carrega_jogo(t_forca* forca) //function that read struct inside bin file
{
FILE* readsave;
readsave = fopen("save.bin", "r b");
if (readsave == NULL)
{
printf("\nerro no arquivo\n");
} //printf error
fread(forca, sizeof(forca), 1, readsave);
fclose(readsave);
}
basically I'm trying to save and read a structure inside a binary file, and I'm quite lost cuz the file is being written but not read at all
CodePudding user response:
In the function carrega_jogo
, forca
is a pointer, sizeof(forca)
is the same as size of pointer, which is 4 or 8 bytes, depending on your system or compiler settings. The read function ends up reading only 4 or 8 bytes. The rest of the structure is likely uninitialized and leads to undefined behavior.
The correct version should be sizeof(t_forca)
Aside, for fwrite/fread
it is enough "wb"
and "rb"
.