定義的結構體:
struct student
{
char ID[11]; //學生學號
char name[20]; //學生姓名
struct student *next; //next 指針 指向 struct student 類型的變量
}stu;
創建文件:
void Create_File_List()
{
FILE *fp;
if ((fp = fopen("student.txt","rb"))==NULL) /*如果此文件不存在*/
{
if ((fp = fopen("student.txt","wb+"))==NULL)
{
outtextxy(220, 200, "無法建立文件!");
}
}
}
寫入文件信息:
/***************
函數功能:錄入出勤學生
/***************/
void add_student( )
{
FILE *fp;
fp=fopen("student.txt","a+");
strcpy(stu.ID,"");// 與鏈表head結點 無數據 有關
strcpy(stu.name,"");
fwrite(&stu,sizeof(struct student),1,fp);
InputBox(stu.ID,11,"請輸入學生學號");
outtextxy(380,200,stu.ID);
Sleep(500);
InputBox(stu.name,20,"請輸入學生姓名");
outtextxy(380,250,stu.name);
Sleep(500);
fwrite(&stu,sizeof(struct student),1,fp);
fclose(fp);
}
這裡值得注意的是:寫入文件的時候,開始時要事先寫入第一個數據,這裡寫入的空數據,這與鏈表head處數據為空有關。
從已經寫入的文件中讀到鏈表中:
/***************
函數功能:創建鏈表
/***************/
struct student * CreateList()
{
struct student *pointer,*head,*q;//head指針為鏈表的頭結點,是找到鏈表的唯一依據,如果head指針丟失,那麼整個鏈表就找不到了;p指針總是指向新申請的結點;q指針總是指向尾節點
struct student temp;//定義結構體別名
FILE *fp;
pointer=(struct student *)malloc(sizeof(struct student )); // p指向新開辟的節點內存
head = pointer; //開辟頭結點內存 頭結點中沒有學生成績信息
q = pointer; //開辟尾節點內存 q指針總是指向尾節點
q->next = NULL; // //標志鏈表的結束 尾節點的特點是next成員的值為NULL,它是最後一個節點,作為鏈表結束的標志,NULL是一個符號常量表示值為0的地址
fp=fopen("student.txt","rb");
while(fread(&temp,sizeof(struct student),1,fp)!=0)//從文件中讀結構體塊
{ pointer=(struct student*)malloc(sizeof(struct student)); // p指向新開辟的節點內存
strcpy(pointer->ID,temp.ID);
strcpy(pointer->name,temp.name);
q->next=pointer; //把新節點掛到原尾節點之後
q=q->next; //q指針指向新的尾節點
}
q->next=NULL;//標志鏈表的結束
fclose(fp);
return head;
}
從鏈表中輸出打印到屏幕中數據:
/*************** 函數功能: 輸出鏈表
返回:指向鏈表表頭的指針 /***************/ void Print_List(struct student *head) { struct student* pointer; pointer=head->next; //跳過無數據的頭結點 while(pointer!=NULL) { outtextxy(x,y,pointer->ID); outtextxy(x,y,pointer->name); pointer=pointer->next;//指向下一個節點 }
}