【发布时间】:2016-03-05 20:18:05
【问题描述】:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
typedef struct node
{
int priorityc;
char *itemName;
struct node *next;
} node;
node *head;
void save();
void printcontents();
int search(char *itemName);
int serve(char *itemName);
void load();
void inserted();
void deleted(char *itemName);
int main()
{
load();
printcontents();
save();
}
void load()
{
head = NULL;
FILE *fp;
fp = fopen("California.txt", "r");
int tempPriority;
char tempName[200];
while(fscanf(fp, "%s %d", tempName, &tempPriority) == 2)
{
//The issue seems to arise somewhere in the remaining code of the load function
node *tempNode = (node *)malloc(sizeof(struct node));
tempNode->priorityc = tempPriority;
tempNode->itemName = tempName;
tempNode->next = head;
head = tempNode;
printf("%s\n", head->itemName);
}
fclose(fp);
printf("%s\n", head->itemName);
}
void printcontents()
{
node *current = head;
while(current != NULL)
{
printf("%s %d\n", current->itemName, current->priorityc);
current=current->next;
}
}
void save()
{
FILE *fp;
node *current = head;
fp = fopen("California.txt", "w");
while(current != NULL)
{
fprintf(fp, "%s %d\n", current->itemName, current->priorityc);
current=current->next;
}
fclose(fp);
}
输入文件 aka California.txt 是一个简单的记事本文件,包含以下信息。
Desktop-computer 100
Desktop-screen 100
Desktop-keyboard 100
TV-set 80
Audio-system 75
Bed 65
Night-table 65
Hibachi 35
在保存功能之后,所有数字都通过了,但以下是控制台打印出来的内容以及在 California.txt 文件中重写的内容。
{°@u&0@ 35
{°@u&0@ 65
{°@u&0@ 65
{°@u&0@ 75
{°@u&0@ 80
{°@u&0@ 100
{°@u&0@ 100
{°@u&0@ 100
我试图将 char tempName(在加载中找到的字符串)变成一个指针并像这样运行函数,但随后控制台打印出来并保存到 california 文件。
Hibachi 35
Hibachi 65
Hibachi 65
Hibachi 75
Hibachi 80
Hibachi 100
Hibachi 100
Hibachi 100
我真的在这里遇到了死胡同,我无法弄清楚如何解决这个问题,任何建议都会有所帮助。如果它工作正常,它应该将以下内容打印到控制台。
Hibachi 35
Night-table 65
Bed 65
Audio-system 75
TV-set 80
Desktop-keyboard 100
Desktop-screen 100
Desktop-computer 100
【问题讨论】:
标签: c pointers struct linked-list nodes