我有这个功能可以打开,读取和关闭文本文件:
void readDataFile()
{
FILE *fp = fopen("AssignmentOneInput.txt", "r"); //opens AssignmentOneInput.txt for reading
char buffer[100];
char *insertName;
char *id;
if (fp == NULL)
{
printf("Error while opening the file.\n");
exit(0);
}
while (!feof(fp))
{
fgets(buffer, sizeof buffer, fp);
insertName = strtok(buffer, ",");
id = strtok(NULL, ",");
insertNode(insertName, id); //function right here is supposed to input information
//into the linked list
}
fclose(fp);
}
这是我的插入功能:
void insertNode(char *insertName, char *id)
{
struct node *temp = malloc(sizeof(struct node));
int intId = atoi(id);
strcpy(temp->name, insertName);
temp->id = intId;
temp->next = head; //rest of the new list is entirety of the current list
head = temp; //head of the new list is the element being inserted
}
我从文本文件中读取信息。我使用strtok将信息解析为令牌并将它们存储到各自的变量中。然后,我在while (!feof(fp))
循环的末尾调用insertNode,将每行信息存储到链表中。但是,信息不会被存储。
每当我在main函数中调用insertNode并运行它时,信息就会毫无问题地存储到链表中。
所以我现在想的是,解析是影响存储的信息还是我的insertNode函数出错了。
有人可以向我解释为什么会这样吗?
答案 0 :(得分:0)
现有代码几乎没有变化
while (fgets(buffer, sizeof buffer, fp) != NULL)
{
insertName = strtok(buffer, ",");
id = strtok(NULL, ",");
if(insertName != NULL && id != NULL)
insertNode(insertName, id);
}