#include <stdio.h>
#include <stdlib.h>
#define SIZE 30
#define N 10
typedef struct{
char name[30];
char no[15];
int sc[3];
float aver;
}STU;
void input_info(STU *stu,int n){
for (int i=0;i<n;i++){
printf("请输入第%d个学生的信息:",i+1);
fscanf(stdin,"%s %s %d %d %d",stu[i].name,stu[i].no,&stu[i].sc[0],&stu[i].sc[1],&stu[i].sc[2]);
stu[i].aver = (stu[i].sc[0]+stu[i].sc[1]+stu[i].sc[2])/3.0;
}
}
void write_info(STU *stu,FILE *fp){
if (NULL == fp) {
printf ("Failed to open the file !\n");
exit(0);
}
fwrite(stu,sizeof(stu),1,fp);
}
void read_info(STU *stu,FILE *fp,int n){
if (NULL == fp) {
printf ("Failed to open the file !\n");
exit(0);
}
rewind(fp);
fread(stu,sizeof(stu),1,fp);
for (int i=0;i<n;i++){
fprintf(stdout,"%s: %s %d %d %d %.2f\n",stu[i].name,stu[i].no,stu[i].sc[0],stu[i].sc[1],stu[i].sc[2],stu[i].aver);
}
}
int main(){
FILE *fp = fopen("info.dat","rb+");
STU stu[N];
int n;
printf("请输入学生的人数:");
/*检测scanf输入的合法性*/
while(1){
if (scanf("%d",&n) == 1)
break;
/*清除stdin缓存流*/
// /*(全平台适用)简单明了效率高*/
scanf("%*[^\n]%*c");//从stdin输入流取出字符直接丢弃
// /*(全平台适用)从stdin输入流取出字符,流是queue结构,最后读到\n*/
// char ch;
// while(ch = getchar()!='\n' && ch != EOF);
// /*windows适用*/
// fflush(stdin);/*直接清空stdin流*/
// /*不太好用*/
// setbuf(stdin, NULL);
printf("输入错误啦!!!你娘个腿儿的!!!\n");
}
input_info(stu,n);
write_info(stu,fp);
read_info(stu,fp,n);
fclose(fp);
return 0;
}
01-02
852
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
07-04
776
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)