首先,抱歉,我知道这个问题被问了很多次,我什至读过一些答案,但仍然没有设法编写工作代码。这是我的基本循环,但它只读取最后一个节点,那么我做错了什么?
谢谢。
这是全局性的:
struct Inventory
{
int cod;
int quant;
float price;
char name[30];
struct Inventory *next;
};
struct Inventory *inventory = NULL;
这是要读取的函数。
void load(void)
{
FILE *ptr;
ptr=fopen("inventory.dat", "rb+");
if (!ptr)
{
return;
}
struct Inventory *p;
while(!feof(ptr))
{
p = malloc(sizeof(struct Inventory));
fread(p, sizeof(struct Inventory), 1, ptr);
p->next = inventory;
inventory = p;
}
fclose(ptr);
}
最佳答案
您将需要另一个变量来存储最新的(当前
)指针。该代码只是一个示例,用于展示指针如何连接。
head
指向列表的开头,current
指向列表中最近添加的内容。 ->prox
指针指向列表中的下一项。
while(!feof(ptr))
{
p = malloc(sizeof(struct Inventory));
if (!head)
{
head = malloc(sizeof(struct Inventory));
current = head;
}
fread(p, sizeof(struct Inventory), 1, ptr);
current->prox = p;
current = p;
}
关于c - 读取二进制文件到链表中,(只读取最后一个节点),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17403302/