0

So, i've this binary file E1.bin and what i need is to read the info there and put it in a dynamic array os structures.

This is my structure where i need to put the info:

    typedef struct sala local, *plocal; 

    struct sala{     
    int id;     
    int capacidade;    
    int liga[3];     
};

The content of the binary file is organized like so: 1 50 3 -1 -1 2 50 3 -1 -1 3 50 1 4 2 (and so on)

Each struct of the array needs to store 5 values: first is for id, second for capacidade, third for liga[0], fourth for liga[1] and fifth for liga[2], then goes to the next struct and does the same.

And this is the function im using to open the file and try to read it:

local *carregaEspaco(local *v, int *tam){

    char espaco[15];

    printf("Nome do ficheiro do espaco a carregar: ");
    gets(espaco);

    FILE *fe = fopen(espaco, "rb");

    if(!fe){
        printf("Erro ao abrir o ficheiro %s.\n\n", espaco);
        return NULL;
    }

    printf("Ficheiro %s aberto.\n\n", espaco);

    local *aux = NULL;
    int i = 1;

    while(fread(&aux, sizeof(local), 1, fe) == 1){

        if(aux == NULL)
            aux = malloc(sizeof(local));
        else
            aux = realloc(v, sizeof(local) * i);

        if(aux){
            v = aux;
            i++;
        }
    }

    *tam = i - 1;    

    fclose(fe);
    return v;
}

I dont understand why isnt this working. Can anyone help me with this please ?

D C
  • 15
  • 7
  • https://www.geeksforgeeks.org/readwrite-structure-file-c/ – Robert Harvey Jun 05 '20 at 14:21
  • Does this answer your question? [Writing Structs to a file in c](https://stackoverflow.com/questions/16997141/writing-structs-to-a-file-in-c) – Robert Harvey Jun 05 '20 at 14:22
  • *is not working* means nothing. Say what is expected and what happens. – Serge Ballesta Jun 05 '20 at 14:26
  • @RobertHarvey not really, i alreayd have that. What i need is to save the info in the array os structs. Like: first five numbers for the first struct, second 5 numbers for the second and so on… and i would like to have a way to confirm that is saving correctly – D C Jun 05 '20 at 14:29
  • I suggest you follow the GeeksForGeeks example, or the example in the "Writing Structs to a file in c" article first. – Robert Harvey Jun 05 '20 at 14:35
  • Thank you for the help, i solved the problem ! – D C Jun 05 '20 at 15:38

0 Answers0