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

标签 c file-io save load

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

编写程序:

#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/

相关文章:

sockaddr_in 结构中 "localhost"的 C Linux 宏?

python - 将 C 的 fread(&struct,....) 移植到 Python

c - gcc 4.4 与 Visual C++ 2008

java - 将文件(.zip、.jar、...)下载到文件夹

c# - 将 richtextbox 保存到文件 C#

c - 无维度的全局整数数组

java - 从文件中读取最后一行

c# - 如何删除文件锁? C#

android - 如何同时捕获相机图像缩略图和完整图像

file - 在 cocoa 中保存文件