0

首先,对不起,我知道这个问题被问了很多我什至读过几个答案,但仍然没有设法编写工作代码。这是我的基本循环,但它只读取最后一个节点,所以我做错了什么?

谢谢。

这是全球性的:

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

1 回答 1

1

您将需要另一个变量来存储最新的 ( current) 指针。该代码只是显示指针如何连接的示例。

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;
}
于 2013-07-01T11:31:29.980 回答