c - 读取二进制文件到链表中,(只读取最后一个节点)

标签 c binary linked-list

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

谢谢。

这是全局性的:

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/

相关文章:

xcode - WatchKit 无效的二进制文件

iphone - 如何在 xCode 中使用 Apple 的崩溃报告?

c - 链表 : Initialize Head with function?

c++ - 我们还需要做静态分析吗?

ios - 如何修复此 YCrCb -> RBG 转换公式?

在 C 中计算 ICMPv6 数据包的校验和

list - Prolog作业: how to parse a list of 'bits' representing a numeric value into a decimal representation?

c - 在不使用 If else 的情况下找出两个数字的最大值和最小值?

java - Java 中的列表列表列表列表列表

java - 节点(和对象)相互分配时实际如何工作