Read char array from a binary file

0

Function that writes and reads the binary file:

int FUNCAO_QUE_GRAVA_BIN (char filename[],int partida1,char resultado1)
{
        typedef struct  {
                int partida;
                char jogvelha[3][3];
                char resultado;
        } velha;

        velha partida = {partida1,{"a","b"},resultado1},read_data;

        FILE * file= fopen(filename, "wb");
        if (file != NULL) {
                fwrite(&partida, sizeof(velha), 1, file);
                fclose(file);

                FILE* fin = fopen(filename, "rb");
                fread(&read_data, sizeof(velha), 1, file);
                printf("%d %c %c\n", read_data.partida, read_data.jogvelha[3][3], read_data.
                       resultado);
                fclose(fin);
                fflush(stdin);
                while(getchar()!='\n'); // option TWO to clean stdin
                getchar(); // wait for ENTER
                return 0;//failure //ignore
        }

        return 1; //sucesso /ignore
}

calling main:

        int ganhador=1;
        char local[]={"binar"};
        int partidas= 1;

  FUNCAO_QUE_GRAVA_BIN(local,partidas,ganhador);

The problem is that the output is going out all wrong, the game [3] [3] does not come out right, how to fix it?

    
asked by anonymous 27.11.2018 / 12:20

1 answer

2

The writing and reading on file that has is correct, the problem are some errors and their mistakes in the code:

  • As I said in commentary printf is wrong because it prints a house that does not exist:

    printf("%d %c %c\n", read_data.partida, read_data.jogvelha[3][3], read_data.resultado);
    //                                                         ^--^
    

    If you have a 3 by 3 board then you have homes 0, 1, and 2. House 3 is already out. It is important to remember that the first home of an array is always 0.

  • Defined resultado as char in structure:

    typedef struct  {
        ...
        char resultado;
    } velha;
    

    But then save the numeric value 1 in this field:

    int ganhador=1;
    FUNCAO_QUE_GRAVA_BIN(local,partidas,ganhador);
    //                                     ^-- aqui passa um int com 1 em vez de um char
    

    This will cause you to see the odd caratere of the ASCII table, more specifically the ASCII caratere 1.

  • The initialization of jogvelha is also wrong:

    velha partida = {partida1, {"a","b"},resultado1}
    //                         ^^^^^^^^
    

    If you have an array of chars 3 by 3 then there are missing characters, just like a missing string. Another detail that you forgot is that if you save the values as strings then the compiler includes the terminator, which causes it to have less space, and needed to have a 4 by 4 board.

    It's best to start with char by typing the characters you want manually:

    velha partida = {partida1, {{'X','O','X'}, {'X','O','X'}, {'X','O','X'}}, resultado1};
    
27.11.2018 / 13:57