C语言建立一个数组将实训12第2题定义的 学生数据存入数组。 数据为: { {"2020B200301","刘滨","男",18,{2020,9,20},70,85}, {"2020B200302","阚美娟","女",17,{2020,9,20},87,95}, {"2020B200303","胡大勇","男",17,{2020,9,20},69,80}, {"2020B200305","黎丽","女",18,{2020,9,20},68,88}, {"2020B200309","金鑫","男",19,{2019,9,1},90,85} } 将这些数据写人磁盘保存起来。
时间: 2023-08-27 20:21:27 浏览: 86
以下是 C 语言实现将学生数据存入数组并写入磁盘的代码:
```c
#include <stdio.h>
struct student {
char id[12]; // 学号
char name[20]; // 姓名
char gender[4]; // 性别
int age; // 年龄
int birthday[3]; // 生日
int score1; // 成绩1
int score2; // 成绩2
};
int main() {
struct student stu[5] = {
{"2020B200301","刘滨","男",18,{2020,9,20},70,85},
{"2020B200302","阚美娟","女",17,{2020,9,20},87,95},
{"2020B200303","胡大勇","男",17,{2020,9,20},69,80},
{"2020B200305","黎丽","女",18,{2020,9,20},68,88},
{"2020B200309","金鑫","男",19,{2019,9,1},90,85}
};
FILE *fp = fopen("students.txt", "w"); // 打开输出文件
if (fp != NULL) { // 如果成功打开文件
for (int i = 0; i < 5; i++) {
fprintf(fp, "%s %s %s %d %d-%d-%d %d %d\n", stu[i].id, stu[i].name, stu[i].gender, stu[i].age,
stu[i].birthday[0], stu[i].birthday[1], stu[i].birthday[2], stu[i].score1, stu[i].score2);
}
fclose(fp); // 关闭文件
} else {
printf("Unable to open file!\n");
}
return 0;
}
```
这段代码定义了一个名为`student`的结构体,与 C++ 代码相同,包含了学生信息的各个字段。然后定义了一个长度为5的`stu`数组,将实训12第2题定义的学生数据存入其中。接着打开一个文件指针,将学生数据写入磁盘文件`students.txt`中,最后关闭文件指针。需要注意的是,在 C 语言中,使用`fprintf()`函数将数据写入文件中。
阅读全文