C-从文件加载链表
因此,我使用二进制文件来保存一些节点状态的信息——系统内部的信息。关键是这个二进制文件有很多1和0,其思想是读取文件并将其加载到结构中。 这是结构的定义:C-从文件加载链表,c,file,C,File,因此,我使用二进制文件来保存一些节点状态的信息——系统内部的信息。关键是这个二进制文件有很多1和0,其思想是读取文件并将其加载到结构中。 这是结构的定义: typedef struct t_bitmap{ int estado; struct t_bitmap* siguiente; }t_bitmap; 这是应该加载它的代码: t_bitmap leerBitmap(char* unPath){ t_bitmap bitmap; FILE *fp = fopen (unPat
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;
};
编辑1
错误是:
不兼容的类型从类型“struct t\u bitmap*”分配给类型“t\u 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);
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;
}
好的你来这里是因为?确定您想要的是链表而不是整数数组吗?还有bitmap.siguiente的值是多少,您是否将其设置在某个位置?它看起来未初始化,这可能导致崩溃。siguiente是指向t_位图的指针。并且类型为t_bitmap的变量bitmap与指针不兼容。每个元素的t_bitmap需要malloc。