#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);
}
基本上,我试图在二进制文件中保存和读取一个结构,而且我非常迷茫,因为文件正在编写,但根本没有读取。
发布于 2021-11-29 04:12:01
在函数carrega_jogo
中,forca
是指针,sizeof(forca)
与指针大小相同,即4或8个字节,这取决于您的系统或编译器设置。read函数最后只读取4或8个字节。结构的其余部分可能未初始化,并导致未定义的行为。
正确的版本应该是sizeof(t_forca)
另外,对于fwrite/fread
来说,"wb"
和"rb"
已经足够了。
https://stackoverflow.com/questions/70149445
复制相似问题