#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);
}
基本上我正在嘗試保存和讀取二進制檔案中的結構,我很迷茫,因為檔案正在寫入但根本沒有讀取
uj5u.com熱心網友回復:
在函式中carrega_jogo,forca是一個指標,sizeof(forca)與指標的大小相同,為 4 或 8 個位元組,具體取決于您的系統或編譯器設定。read 函式最終只讀取 4 或 8 個位元組。結構的其余部分可能未初始化并導致未定義的行為。
正確的版本應該是 sizeof(t_forca)
順便說一句,因為fwrite/fread它足夠了"wb"并且"rb"。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/368960.html
