首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >功能误区

功能误区
EN

Stack Overflow用户
提问于 2021-11-29 03:29:44
回答 1查看 48关注 0票数 1
代码语言:javascript
运行
复制
#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);
}

基本上,我试图在二进制文件中保存和读取一个结构,而且我非常迷茫,因为文件正在编写,但根本没有读取。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-11-29 04:12:01

在函数carrega_jogo中,forca是指针,sizeof(forca)与指针大小相同,即4或8个字节,这取决于您的系统或编译器设置。read函数最后只读取4或8个字节。结构的其余部分可能未初始化,并导致未定义的行为。

正确的版本应该是sizeof(t_forca)

另外,对于fwrite/fread来说,"wb""rb"已经足够了。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70149445

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档