写/读二进制保存游戏

时间:2015-12-07 17:39:14

标签: 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中的行,而是显示不同的字符。

我知道代码中可能存在很多错误,但我仍然是初学者,所以真的对任何帮助表示赞赏!

1 个答案:

答案 0 :(得分:1)

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

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