二进制文件写入:建立一个成绩结构体,包括:成绩单号,语文分数、数学分数;随机生成10人成绩写入文件c:\score.dat
时间: 2024-02-29 17:56:49 浏览: 21
好的,下面是代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// 成绩结构体
typedef struct {
int id;
int chinese;
int math;
} Score;
int main() {
// 随机数种子
srand((unsigned)time(NULL));
// 创建文件指针
FILE *fp;
fp = fopen("c:\\score.dat", "wb");
if (fp == NULL) {
printf("File open error!\n");
exit(1);
}
// 随机生成10个成绩并写入文件
for (int i = 1; i <= 10; i++) {
Score score;
score.id = i;
score.chinese = rand() % 101;
score.math = rand() % 101;
fwrite(&score, sizeof(Score), 1, fp);
}
// 关闭文件
fclose(fp);
return 0;
}
```
以上代码会在C盘根目录下创建一个二进制文件score.dat,并将10个随机生成的成绩写入其中。每个成绩包括成绩单号、语文分数和数学分数,都是随机生成的。