单链表写入文件
#include <stdio.h>#include <stdlib.h>
#include <string.h>
typedef struct node
{
int sno;
char name[128];
}TYPE;
typedef struct student
{
TYPE data;
struct student *next;
}STU;
static FILE *fp;
void add();
void visit();
void destroy(STU *);
int main()
{
while(1)
{
printf("============================\n");
add();
printf("=============================\n");
visit();
}
fclose(fp);
return 0;
}
void add()
{
fp=fopen("stu.txt","a+");
char ch;
if((ch=fgetc(fp))==EOF)
{
STU *st=(STU *)malloc(sizeof(STU));
printf("请输入学号!\n");
scanf("%d",&st->data.sno);
printf("请输入姓名!\n");
scanf("%s",st->data.name);
st->next=NULL;
fwrite(st,sizeof(STU),1,fp);
free(st);
}
else
{
STU *head;
rewind(fp);
fread(head,sizeof(STU),1,fp);
//获取尾节点
STU *last=head;
for(;last->next != NULL;)
last=last->next;
//新节点的添加
STU *st=(STU *)malloc(sizeof(STU));
printf("请输入学号!\n");
scanf("%d",&st->data.sno);
printf("请输入姓名!\n");
scanf("%s",st->data.name);
last->next=st;
st->next=NULL;
fwrite(st,sizeof(STU),1,fp);
free(st);
}
}
void visit()
{
fp=fopen("stu.txt","r");
if(fp==NULL)
{
printf("error!\n");
exit(1);
}
STU *head;
rewind(fp);
fread(head,sizeof(STU),1,fp);
if(head!= NULL)
for(;head != NULL;head=head->next)
printf("学号:%d 姓名:%s\n",head->data.sno,head->data.name);
else
printf("数据库数据为空!\n");
}
请各位大大帮忙看一下,为什么链表的数据写不进文件,谢谢了!