读取文件时多了一条乱码,希望大家斧正
我做的一个成绩管理系统,但是保存到文件里面后在读取出来就多了一条乱码的记录,希望大家斧正保存函数如下:
void save(STU *head) //保存记录的函数
{
FILE *fp;
STU *p1;
char name[15];
char state = 0; //保存是否成功的状态,成功保存则为0,失败为1
if(head == NULL)
printf("\nlist null!");
else
{
p1 = head;
printf("\n请输入保存记录的名字(少于15个字符):");
scanf("%s",name);
if((fp = fopen(name,"w+")) == NULL)
printf("\ncannot open this file");
else
{
do
{
if(fwrite(p1,LEN,1,fp) != 1)
{
printf("\nfile write error!\n");
state = 1;
break;
}
p1 = p1->next;
}while(p1 != NULL);
if(state == 0)
printf("\nThe %d records save scuccee!\n",n);
fclose(fp);
}
}
}
读取函数如下:
STU *read(void) //读取记录的函数
{
FILE *fp;
STU *head;
STU *p1,*p2;
char name[15];
head = NULL;
printf("\n请输入读取记录的名字(少于15个字符):");
scanf("%s",name);
if((fp = fopen(name,"r+")) == NULL)
{
printf("\nfile cannot open");
return(head);
}
else
{
n = 0;
head = (STU *)malloc(LEN);
p1 = head;
do
{
fread(p1,LEN,1,fp);
p2 = p1;
p1 = (STU *)malloc(LEN);
p2->next = p1;
n++;
}while(!feof(fp));
p2->next = NULL;
free(p1);
return(head);
fclose(fp);
}
}