Search code examples
cfilefwrite

C - How to persist array if struct in file


This is what i got so far but im not actually writing on the file. I think im not using correctly fwrite()

typedef struct t_directory {
  int index;
  char nombre[255];
  int padre;
}t_directory;

int main(void) {

    t_directory* tabla[100];

    int i;
    for(i=0; i<100;i++){
        tabla[i] = malloc(sizeof(struct t_directory));
        tabla[i]->index = 0;
        sprintf(tabla[i]->nombre, "");
        tabla[i]->padre = 0;
    }

    tabla[0]->index = 0;
    sprintf(tabla[0]->nombre, "root");
    tabla[0]->padre= -1;

    tabla[1]->index = 1;
    sprintf(tabla[1]->nombre, "user");
    tabla[1]->padre= 0;

    FILE * file= fopen("directorios.txt", "wb");
    if (file != NULL) {
        fwrite(tabla[0], sizeof(struct t_directory), sizeof(struct t_directory), file);
        for(i=1;i<100;i++){
            if(tabla[i]->index != 0){
                fwrite(tabla[i], sizeof(struct t_directory), sizeof(struct t_directory), file);
            }
        }
        fclose(file);
    }

How should i be doing it?


Solution

  • First of all, the file is binary so you should not really be able to read it as text.

    Secondly, and the source of your problem, is how you write the structure:

    fwrite(tabla[0], sizeof(struct t_directory), sizeof(struct t_directory), file);
    

    If you read e.g. this fwrite reference you will see that the two size-arguments is:

    1. Size of the data structure
    2. The number of data structures

    You get the second size-argument wrong, and the call attempts to write in total sizeof(struct t_directory) * sizeof(struct t_directory) bytes to the file, every time you call fwrite.

    Correct should be to write one structure:

    fwrite(tabla[0], sizeof(struct t_directory), 1, file);
    //                                           ^
    // Note the value one here, to write only a single structure
    

    If you don't care about the space on the disk (which will be minimal for your table) then I suggest you write the whole array in one go instead.

    For this to work you of course need to have an array of objects instead of pointers:

    t_directory tabla[100];
    

    Then you could write it all in one call:

    fwrite(tabla, sizeof tabla[0], sizeof tabla / sizeof tabla[0], file);