这里是我的代码的编辑版本以及创建列表的函数。start初始化为全局变量,start=NULL。我也改变了我的写作方式。我没有枚举一长串变量,而是使用buf来获取其内容(即名称、标题、类型…)。mygets只是我创建的一个函数,用于删除后面的。同样的问题也出现了。外国符号出来了。
void saving()
{
FILE *out;
struct node buf;
struct node *current;
out = fopen("foo", "wb");
if(out == NULL) return;
printf("Writing to file...");
while(current != NULL)
{
fwrite(&buf, sizeof(struct node), 1, out);
}
printf("Done!\n");
fclose(out);
}
void create()
{
node *p,*q;
int item;
char ti[STRLEN],na[STRLEN],ty[6];
printf("Warrior name: ");
mygets(na);
printf("\nWarrior title: ");
mygets(ti);
printf("\nWarrior Type and Class Encoding: ");
fgets(ty,6,stdin);
p=(node *)malloc(sizeof(node));
strcpy(p->name,na);
strcpy(p->title,ti);
strcpy(p->type,ty);
p->next=NULL;
if(start==NULL)
{
start=p;
}
else
{
q=start;
while(q->next!=NULL)
{
q=q->next;
}
q->next=p;
}
}
最佳答案
正如Baldrick在他的评论中指出的,您还没有将current
分配给链表的start/head节点。
你这样做,解除对一个未初始化指针的引用,可能导致你的程序崩溃,幸运的是对你来说不是这样。
使用:
struct node *current = head; // Or whatever is your head node name
顺便说一下,如果你写一个二进制文件,最好不要把它命名为foo.txt,使用诸如.bin,.dat等二进制扩展名,或者最好不要使用任何扩展名。