Marco
Marco

Reputation: 1172

C - Load linked list from file

So im using binary files to save info about the state of some nodes (something internal of the system). The point is this binary files are just a lot of 1 and 0 and the idea is to read the file and load it into a struct. This is the definition of the struct:

typedef struct t_bitmap{
int estado;
struct t_bitmap* siguiente;
}t_bitmap;

And this is the code that is supposed to load it:

t_bitmap leerBitmap(char* unPath){
    t_bitmap bitmap;
    FILE *fp = fopen (unPath, "rb");
    int i=0;
    fseek(fp, 0, SEEK_END);
    int tamanio = sizeof(char) * ftell(fp);
    fseek(fp, 0, SEEK_SET);
    char* bytes = malloc(tamanio);
    fread(bytes, tamanio, 1, fp);
    fclose (fp);
    while(i<tamanio){
        bitmap.estado = bytes[i];
        bitmap = bitmap.siguiente; //This fails
        i++;
    };
    free(bytes);
    return bitmap;
};

EDIT 1

The error is: incompatible types when assigning to type ‘t_bitmap’ from type ‘struct t_bitmap *’

Upvotes: 0

Views: 178

Answers (1)

Stephan Lechner
Stephan Lechner

Reputation: 35154

You need to allocate a new node for each byte you read in.

Usually one would define the function such that it returns a pointer to the head of a linked list (which could be NULL if no value can be read in).

In order not to change the prototype of your function, I kept the "return-by-value"-metaphor for the head of the list.

So the function allocates a new node for each byte, except for the first byte, which is stored directly in the "head" that will be returned by value:

t_bitmap leerBitmap(char* unPath){
    t_bitmap bitmap;
    FILE *fp = fopen (unPath, "rb");
    int i=0;
    fseek(fp, 0, SEEK_END);
    int tamanio = sizeof(char) * ftell(fp);
    fseek(fp, 0, SEEK_SET);
    char* bytes = malloc(tamanio);
    fread(bytes, tamanio, 1, fp);
    fclose (fp);

    t_bitmap* curBitMap = &bitmap; // the current bitmap to write to
    while(i<tamanio){
        if (i > 0) { // except for the first, create a new node
            curBitMap->siguiente = malloc(sizeof(t_bitmap));
            curBitMap = curBitMap->siguiente;
        }
        curBitMap->estado = bytes[i];
        curBitMap->siguiente = NULL;
        i++;
    };
    free(bytes);
    return bitmap;
}

Upvotes: 1

Related Questions