221001 张三 男 2004-3-15 85 9585 221002 李四 女 2005-12-10 90 8095 221003 王五 男 2004-4-12 75 8080 221004 刘一 男 2003-12-5 82 8886 221005 陈二 男 2004-1-10 80 9285 221006 赵六 女 2005-6-18 88 8598
时间: 2023-09-02 15:15:02 浏览: 36
好的,以下是读取data1.txt文件,计算总分并写入data1.bin文件的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include "student.h"
int main(){
FILE *fp;
Student a[6];
int i;
float sum = 0;
// 从data1.txt文件中读取学生信息到数组a中
fp = fopen("data1.txt", "r");
if(fp == NULL){
printf("无法打开文件!\n");
exit(1);
}
for(i=0; i<6; i++){
fscanf(fp, "%s %s %c %d-%d-%d %f %d", a[i].id, a[i].name, &a[i].gender, &a[i].birthday.year, &a[i].birthday.month, &a[i].birthday.day, &a[i].score, &a[i].rank);
sum += a[i].score; // 计算学生总分
}
fclose(fp);
// 将学生总分保存到数组a中
for(i=0; i<6; i++){
a[i].total_score = sum;
}
// 将数组a中的学生信息以二进制形式写入data1.bin文件中
fp = fopen("data1.bin", "wb");
if(fp == NULL){
printf("无法打开文件!\n");
exit(1);
}
fwrite(a, sizeof(Student), 6, fp);
fclose(fp);
printf("学生总分为:%.2f\n", sum);
return 0;
}
```
请注意,这里使用了student.h中定义的Student结构体,如果您没有提供该文件,请先定义该结构体,再使用以上代码。
运行程序后,会生成data1.bin文件,您可以使用记事本打开该文件查看其二进制内容。
同时,以下是student.h文件的内容:
```c
#ifndef _STUDENT_H_
#define _STUDENT_H_
typedef struct {
char id[10]; // 学号
char name[20]; // 姓名
char gender; // 性别
struct {
int year;
int month;
int day;
} birthday; // 出生日期
float score; // 成绩
int rank; // 排名
float total_score; // 总分
} Student;
#endif
```