Question

So, I'm having trouble reading from my file.

I want to read this file ;

    1

0 0 0 0 0 0 0 0
0 0 0 2 0 0 0 0
0 0 0 2 0 0 0 0
0 0 0 2 1 0 0 0
0 0 1 2 2 0 0 0
0 1 0 0 0 0 0 0
0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 

The first 1 is my player, while the array is my game board.

So I'm trying to read all this using this code :

void initialize_file(Game *game)
{
    int i,j;
    FILE *file = fopen("save.sav", "r");
    if(file==NULL)
    {
        printf("Can't read file.... \n");
    }
    else
    {
        game->player=(fgetc(file)-'0');
        printf("Player %d loaded\n",jeu->player);
        fgetc(file); //jump the two lines after player
        fgetc(file);
        for(i=0;i<8;i++)
        {
            for(j=0;j<8;j++)
            {
                Game->game[i][j] = (fgetc(file)-'0');
                printf("value : %d \n",Game->game[i][j]);
                fgetc(file);

            }
            fgetc(file);
        }
    }
}

My problem is that I sometimes get values outside of my array like -16 and -38, which refer each to Space and LF. So my question is : How could I avoid to run unto these -16 and -38 ?

Thanks a lot, and I am sorry in advance for any english mistakes

Was it helpful?

Solution 2

Does a blank exist after the last value on each line?

If the line ends with '0\n' instead of '0 \n', the invocation of fgetc in the inner loop will read the \n the first time the loop terminates, and the outer loop will read the next character. This will cause your arithmetic to result in ' ' - '0' many times, which is 32-48 = -16 on a system that uses a character encoding compatible with ASCII.

Similarly, '\n' - '0' is 10-48 = -38. Your problem is that the last number on each line is not followed by a blank.

Either output a blank before the \n when you save your game board or remove the last invocation of fgetc since the inner loop already reads the \n.

Edit: As cnicutar responded, you should also be checking your return values.

OTHER TIPS

Every time you do an c = fgetc(..) check c != EOF and isdigit(c) before using it.


Word to the wise, c should be an int. But of course everyone knew that.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top