按学号从小到大输入学号id,姓名name,语文china,数学math,英语english,在已存的信息中插入一个人(按学号排列)
<span style="font-size:18px;">#include <iostream>
#include <cstdio>
#include <string>
#include <cmath>
#include <cstdlib>
using namespace std;
typedef struct student
{
int id;
char name[20];
int china ;
int math;
int english;
}Stu;
int main()
{
Stu stu,stu1;
int i,flag=1;
FILE *fp,*fp1;
fp=fopen("d:\\stud.txt","wb");
if(fp==NULL)
return -1;
for(i=0;i<5 ;i++)//将信息保存到文件中
{
scanf("%d%s%d%d%d",&stu.id,stu.name,&stu.china,&stu.math,&stu.english);
fwrite(&stu,sizeof(Stu),1,fp);
}
fclose(fp);
fp=fopen("d:\\stud.txt","rb");
if(fp==NULL)
return -1;
fp1=fopen("d:\\stud1.txt","wb+");
if(fp1==NULL)
return -1;
scanf("%d%s%d%d%d",&stu.id,stu.name,&stu.china,&stu.math,&stu.english);
while(fread(&stu1,sizeof(Stu),1,fp)!=0)//插入操作
{
if(flag && stu1.id>stu.id)
{
fwrite(&stu,sizeof(Stu),1,fp1);//fwrite与fread只能对二进制信息进行操作
flag=0;
}
fwrite(&stu1,sizeof(Stu),1,fp1);
}
if(flag==1)
fwrite(&stu,sizeof(Stu),1,fp1);
rewind(fp1);
while(fread(&stu,sizeof(Stu),1,fp1)!=0)//输出
{
printf("%d\t%s\t%d\t%d\t%d\n",stu.id,stu.name,stu.china,stu.math,stu.english);
}
fclose(fp);
fclose(fp1);
return 0;
}</span>