C - 从文件加载链接列表

问题描述:

所以即时通讯使用二进制文件来保存有关某些节点(系统内部的东西)状态的信息。关键是这个二进制文件只是很多的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

您需要分配为每个在读字节的新节点。

一般人会定义的函数,它返回一个指向链表的头(可能是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; 
}