初学者的问题:c语言中链表写入文件的问题(为什么我只能写如最后一个节点的数据)???
kaz33 2008-04-20 11:24:32 小弟刚来社区分数不多,恳请请高手指点指点!!!!!!!这是我的代码,我想把每个节点都存储到文件里,为什么只能存最后一个的??请说具体一点的步骤,该怎么做,谢谢各位啦!!!!!!!!!!!!!
#include <stdio.h>
#include <string.h>
struct student
{
char num[4];
char name[4];
student* next;
};
void printFile(char* desFile,student* p)
{
FILE* pFile=fopen(desFile,"w");
fprintf(pFile,"%s,%s\n",p->num,p->name);
fclose(pFile);
}
student* head=NULL;
void createLine(char* num,char* name)
{
student* newp=new student;
strcpy(newp->num,num);
strcpy(newp->name,name);
newp->next=NULL;
printFile("d:\\student.txt",newp);
if(head==NULL)
{
head=newp;
}
else
{
newp->next=head;
head=newp;
}
}
void printLine()
{
student* temp=head;
while(temp!=NULL)
{
printf("%s %s\n",temp->num,temp->name);
temp=temp->next;
}
}
void main()
{
char num[4];
char name[4];
for (int i=0; i<3; i++)
{
scanf("%s %s",num,name);
createLine(num,name);
}
printLine();
}