关于链表的读写,请高手指导
这是一段链表的c程序,想实现的的是通过读取文件建立链表(ReadData()),头插法加入新的链表(AddPassenger()),写入更改后的内容(WriteData())。编译通过后跑起来就崩,应该是内存上的问题,但不知道怎么改,请大神改下。程序代码:
#include <stdio.h> #include <stdlib.h> #define D:\\ FILENAME //全局变量 typedef struct passenger{ struct passengerData{ char login_ID[200]; char password[99]; char name[20]; }*passengerDATA; struct passenger *next; }PASSENGER; PASSENGER *head=NULL; int ReadData(); PASSENGER* AddPassenger(); int WriteData(); int main() { ReadData(); AddPassenger(); WriteData(); } int WriteData() { PASSENGER *p; FILE *fp; fp=fopen("FILENAME","wb"); if(fp==NULL) { printf("open error\n"); return 1; } p=head; while(p!=NULL) { if(fwrite(p->passengerDATA,sizeof(struct passengerData),1,fp)!=1) printf("Error"); else p=p->next; } fclose(fp); return 0; } PASSENGER* AddPassenger() { PASSENGER *newMem; printf("to creat a new account\n"); newMem=(PASSENGER*)malloc(sizeof(PASSENGER)); printf("The ID\n"); scanf("%s",newMem->passengerDATA->login_ID);//->左边必须是指针类型,否则只能用.来寻址 printf("The pssword\n"); scanf("%s",newMem->passengerDATA->password); printf("The name\n"); scanf("%s",newMem->passengerDATA->name); newMem->next=head; head=newMem; return head; } int ReadData()//0正确,1错误 { PASSENGER *newMem,*tail; int i; FILE *fp; fp=fopen("FILENAME","rb"); if(fp==NULL) { printf("open Failed\n"); return 1; } newMem=(PASSENGER*)malloc(sizeof(PASSENGER)); while(feof(fp)!=0) if(fread(head->passengerDATA,sizeof(struct passengerData),1,fp)==1){ head=newMem; newMem->next=tail; tail=head; free(fp); newMem=(PASSENGER*)malloc(sizeof(PASSENGER)); } fclose(fp); return 0; }