gpt4 book ai didi

c - 写入/读取二进制保存游戏

转载 作者:行者123 更新时间:2023-11-30 15:14:12 28 4
gpt4 key购买 nike

我目前正在开发一个保存和加载程序,但我无法获得正确的结果。

编写程序:

#include <stdio.h>
#include <stdlib.h>
#define FILENAME "Save"
#define COUNT 6

typedef struct
{
unsigned Activeplayer;
char row[7];
} Savegame;

int main()
{
char rowA[7]={'A','-','-','-','-','-','-'};
char rowB[7]={'B','-','-','-','-','-','-'};
char rowC[7]={'-','-','-','-','-','-','-'};
char rowD[7]={'-','-','-','-','-','-','-'};
char rowE[7]={'-','-','-','-','-','-','-'};
char rowF[7]={'-','-','-','-','-','-','-'};
int activeplayer = 2;

Savegame product[COUNT] = {{ activeplayer, rowA},
{ activeplayer, rowB},
{ activeplayer, rowC},
{ activeplayer, rowD},
{ activeplayer, rowE},
{ activeplayer, rowF},
};

FILE *output = fopen(FILENAME, "wb+");
if (output) // file opened OK
{
int written = fwrite(product, sizeof(Savegame), COUNT, output);
printf("%d records written to file.\n", written);
fclose(output);
}
return 0;
}

一切都可以正常编译并创建一个二进制文件。然后我编写了另一个程序,它应该打印出行和 Activeplayer:

#include <stdio.h>
#define FILENAME "Save"
#define COUNT 6

typedef struct
{
unsigned Activeplayer;
char row[7];
} Savegame;

int main()
{
FILE *input = fopen(FILENAME, "r"); // read
Savegame *temp = (Savegame*) malloc(sizeof(Savegame));
if (input) // file opened OK
{
while (fread(temp,sizeof(Savegame),1,input))
{
printf("%s: %d\n",temp->row,temp->Activeplayer);
}
}
free(temp);
fclose(input);
return 0;
}

当我编译程序时,它不显示程序 A 中的行,而是显示不同的字符。

我知道代码中可能有很多错误,但我仍然是初学者,所以非常感谢任何帮助!

最佳答案

正如您以二进制形式编写的文件一样。您应该以二进制模式读取该文件。试试这个:

FILE *input = fopen(FILENAME, "rb");  // read

关于c - 写入/读取二进制保存游戏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34139779/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com