我希望您能够帮助翻译一个关于IT技术的文本,该文本与创建通讯录程序有关,需要从文件中读取数据并将其存储到列表中的特定节点中。如果我使用静态数据(例如使用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;
}
}
tempNode->firstName = strdup(fn);
。 - R Samuel Klatchkostrdup
不是 ISO C 标准函数,但它是 POSIX 标准函数。 - Alok Singhal