gpt4 book ai didi

c - 将文件数据读入 C 中的链表

转载 作者:搜寻专家 更新时间:2023-10-30 19:44:41 24 4
gpt4 key购买 nike

我正在尝试创建一个简单的电话簿程序,该程序从文件中读取数据并将内容存储到列表中的特定节点中。如果我将我的 addEntry 函数与静态数据一起使用,它工作正常,例如:

addEntry("First", "Last", "555-555-5555");

如果我尝试从文件中读取超过 1 个条目,则每个条目看起来都是文件中的最后一个条目。例如,如果我的文件包含:

First1
Last1
123-456-7890
First2
Last2
987-654-3210

将数据存储到列表中并打印后,输出如下所示:

First2
Last2
987-654-3210

First2
Last2
987-654-3210

而不是打印每个特定的名称和号码。这让我很困惑,因为这个问题只发生在我从文件中读取数据时,而不是当我在函数调用中手动输入名称和号码时。以下是 main 和 addEntry 的定义,在此先感谢您。

#include <stdlib.h>
#include <stdio.h>

struct bookNode
{
char * firstName;
char * lastName;
char * phoneNumber;
struct bookNode * next;
} * head;

FILE * fpointer;

void addEntry(char * fn, char * ln, char * pn);
void display();
int numEntries();
void writeBookData(struct bookNode * selection);

int main()
{
head = NULL;
addEntry("Test", "Name", "111-111-1111");
addEntry("Test2", "Name2", "222-222-2222"); // These entries will work as intended

int i;
fpointer = fopen("addressbook.dat", "a+");
if(fpointer == NULL)
{
printf("Error: addressbook.dat could not be opened.\n");
}

char first[20];
char last[20];
char num[20];

while (!feof(fpointer))
{
fgets(first, 20, fpointer);
fgets(last, 20, fpointer);
fgets(num, 20, fpointer);

//Removes newline characters from the ends of the names
i = 0;
while(first[i] != '\n')
{
i++;
}
first[i] = '\0';
i = 0;
while(last[i] != '\n')
{
i++;
}
last[i] = '\0';

// Adds the entry from the strings with the file data in them
addEntry(first, last, num);
}
fclose(fpointer);

display(); // typical linked list display function

int entryCount = numEntries();
printf("There are %d entries in this Address Book\n", entryCount);

return EXIT_SUCCESS;
}

void addEntry(char * fn, char * ln, char * pn)
{
struct bookNode * tempNode, * iterator;
tempNode = (struct bookNode *)malloc(sizeof(struct bookNode));
tempNode->firstName = fn;
tempNode->lastName = ln;
tempNode->phoneNumber = pn;
iterator = head;

// If the list is empty
if (head == NULL)
{
head = tempNode;
head->next = NULL;
}

// The list is not empty
else
{
while(iterator->next != NULL)
{
iterator = iterator->next;
}
tempNode->next = NULL;
iterator->next = tempNode;
}
}

最佳答案

您需要将字符串值复制到每个新节点。您只存储指向每个字符串的指针,但它始终是相同的指针(在 main 中声明的 first、last 和 num),因此它们都指向相同的内存。

所以在你的addEntry方法中,你需要先分配内存来存储字符串,然后将字符串复制到新的内存中。

您手动添加条目的示例有效,因为 char 指针指向静态字符串。

所以在你的 addEntry 方法中你应该做这样的事情:

tempNode = (struct bookNode *)malloc(sizeof(struct bookNode));
tempNode->firstName = (char *)malloc(strlen(fn)+1);
strcpy(tempNode->firstName, fn);

然后相同的姓氏和电话。请记住,您需要遍历列表并为每个字符串以及列表中的节点释放内存。

关于c - 将文件数据读入 C 中的链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2075497/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com