C语言二进制文件读写问题,求高手赐教!
只要进行两次输入,然后再输出数据。就会出错,不知怎么回事。。。void input_date()
{
FILE *fp, *frecord_date;
char filename[20];
int i, j;
float sum;
printf("请输入新建文件名:");
gets(filename);
if((fp=fopen(filename,"wb"))==NULL)
{
printf("无法打开文件!");
exit(0);
}
if((frecord_date=fopen("record_date.txt","r+"))==NULL)
{
printf("无法打开文件!");
exit(0);
}
fscanf(frecord_date,"%d",&date_sum);
fclose(frecord_date);
fseek(fp,0,SEEK_END);//把文件指针调到最后,再写数据
printf("请输入学生数据,以学号0结束\n");
stu[0].num=1;//保证输入开始
for(i=date_sum; ; i++)
{
printf("NO. ");
scanf("%ld",&stu[i].num);
getchar();
if(stu[i].num==0)//退出输入
break;
printf("name: ");
gets(stu[i].name);
sum=0;
for(j=0; j<3; j++)
{
printf("第%d科:",j+1);
scanf("%f",&stu[i].score[j]);
sum=sum+stu[i].score[j];
}
getchar();
stu[i].aver=sum/3;
if(fwrite(&stu[i], sizeof(struct student), 1, fp)!=1) //二进制读写
{
printf("error!");
fclose(fp);
}
}
printf("执行完毕!");
fclose(fp);
date_sum=i; //记录数据总数
if((frecord_date=fopen("record_date.txt","w"))==NULL)
{
printf("无法打开文件!");
exit(0);
}
fprintf(frecord_date,"%d",date_sum);//记录数据
fclose(frecord_date);
}
///////////////////////////////////////
void output_date()
{
FILE *fp, *frecord_date;
char filename[20];
int i, j;
printf("请输入需要打开的文件名:");
gets(filename);
if((fp=fopen(filename,"rb"))==NULL)
{
printf("无法打开文件!");
exit(0);
}
if((frecord_date=fopen("record_date.txt","r"))==NULL) //打开记录数据数目的文件
{
printf("无法打开文件!");
exit(0);
}
fscanf(frecord_date,"%d",&date_sum);
printf("date_sum=%d\n",date_sum);
fseek(fp,0,SEEK_SET);
for(i=0; i<date_sum; i++)
{
if(fread(&stu[i], sizeof(struct student), 1, fp)!=1)//读数据
{
printf("error!");
fclose(fp);
}
printf("NO.%d\n",stu[i].num);
printf("name:%-10s\n",stu[i].name);
for(j=0; j<3; j++)
{
printf("第%d科: ",j+1);
printf("%-5.2f\n",stu[i].score[j]);
}
printf("平均分:%-5.2f\n",stu[i].aver);
printf("\n");
}
printf("执行完毕!");
fclose(frecord_date);
fclose(fp);