接着写文件的问题
编写了个程序:从b.txt文件提取数据,排序后在写入原文件
我发现总是在同程序中先关了b.txt,在打开b.txt,才能接着写入内容。
是怎么回事.
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
struct student
{
int num;
char name[20];
float score[3];
float ever;
}b[6],a[5];
int main()
{
FILE *fp,*fp1;
struct student y;
int i,j,k;
float sum=0;
printf("shu ru xu shen chengji:\n");
scanf("%d%s%f%f%f",&b[5].num ,&b[5].name ,&b[5].score[0],&b[5].score[1],&b[5].score[2]);
b[5].ever=(b[5].score[0]+b[5].score[5]+b[5].score[2])/3;
if((fp=fopen("E:\\c语言\\b.txt","r+"))==NULL)
{
printf("da kai wen jian shi bai:");
exit(0);
}
for(i=0;i<5;i++)
fscanf(fp,"%d%s%f%f%f%f",&b[i].num ,&b[i].name ,&b[i].score[0],&b[i].score[1],&b[i].score[2],&b[i].ever);
for (i=0;i<6;i++)
for(j=i+1;j<6;j++)
if(b[i].ever<b[j].ever)
{y=b[i];
b[i]=b[j];
b[j]=y;}
if((fp=fopen("E:\\c语言\\b.txt","a+"))==NULL) // 这里又打开了文件一次,没有这个就不能接着写入b.txt(原来内容不变)
{ printf("da kai wen jian shi bai:");
exit(0);
}
for(i=0;i<6;i++)
{ printf("%5d%10s%8.2f%8.2f%8.2f%8.2f\n",b[i].num ,b[i].name ,b[i].score[0],b[i].score[1],b[i].score[2],b[i].ever );
fprintf(fp,"%5d%10s%8.2f%8.2f%8.2f%8.2f\n",b[i].num ,b[i].name ,b[i].score[0],b[i].score[1],b[i].score[2],b[i].ever);
}
fclose(fp);
return 0;
}
b.txt内容是
102 ekjl 85.00 96.00 74.00 85.00
105 klj 65.00 98.00 32.00 65.00
101 li 89.00 56.00 23.00 56.00
104 kdfsjl 87.00 54.00 21.00 54.00
103 kjg 78.00 45.00 12.00 45.00
要插入的内容是 106 dlsk 98 78 56
那位高手帮忙看看,谢谢