This is the last thing I have to implement in my code and the game will be completed.
I need to be able to save and load game. For that I save the values of the cells in a txt file in the following manner:
Code:
int SaveGame(jogo_4line *jg)
{
FILE *fp;
int n;
char *lines[MAXLINES];
fp=fopen("SavedGame","w");
if (!fp)
{
printf("Error creating file\n");
return 0;
}
for (n = 0; n < MAXLINES; n++)
{
lines[n] = LinGameToStr (jg, n);
fprintf(fp,"%s\n",lines[n]);
}
fclose(fp);
return 1;
}
The SavedGame file could look like this (ofc this would be impossible but you get the point)
XXOOOXXX
XXOOOXXX
XXOOOXXX
XXOOOXXX
XXOOOXXX
XXOOOXXX
But I having a hard time in the loadgame function:
Code:
int LoadGame( jogo_4line *jg)
{
int n=0;
FILE *fp;
char *lines=malloc(8);
fp=fopen("SavedGame","r");
if (!fp)
{
printf("File not found\n");
return 0;
}
while(fscanf(fp,"%s",lines)==1)
{ printf("%d - %s\n",n,lines);
n++;
}
free(lines);
fclose(fp);
return 1;
}
(I do a printf in the while cycle to inspect the output)
The problem is, when the fscanf finds a SPACE (cell where no one has played it), it stops reading and assigns the rest of the line (after the space) to a new line.
So, if SavedGame file looks like this,
line 0 - OOXOXOO
line 1 - XXXO XX
line 2 - XOOO
line 3 - O XX
line 4 -
line 5 -
The printf output will be
0 - OOXOXOO
1 - XXXO
2 - XX
3 - XOOO
4 - O
5 - XX
And this is no good. How can I get around this?
Here is a printscreen of the situation I described here to make it easier for you guys to understand: