2017-09-16 82 views
0

所以即時通訊使用二進制文件來保存有關某些節點(系統內部的東西)狀態的信息。關鍵是這個二進制文件只是很多的1和0,想法是讀取文件並將其加載到結構中。 這是該結構的定義:C - 從文件加載鏈接列表

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

而這是應該加載它的代碼:

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

的錯誤是: 不相容從類型'struct t_bitmap *'分配類型't_bitmap'時的類型

+3

好。你在這裏是因爲...? – zerkms

+0

指針'struct'成員僅在上下文中相關。你無法從文件中有效地讀取它們 - 如果你得到了那麼多。 –

+0

@zerkms我不知道如何穿過位圖給每個estado值。我指出哪一行失敗。 – Marco

回答

1

您需要分配爲每個在讀字節的新節點。

一般人會定義的函數,它返回一個指向鏈表的頭(可能是NULL如果沒有值可以讀)。

爲了不改變你函數的原型,我保留了列表頭部的「按值返回」--metaphor。

所以函數分配一個新的節點對每個字節,除了第一個字節,其被直接存儲在「頭」將由值被返回:

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; 
}