请你编写一个程序完成将三位学生信息写入二进制文件class.dat的功能,学生信息由键盘读入,存储在一个结构体数组中。 该结构体数组的定义如下: typedef struct studentMessage { char name[20]; char address[30]; char phone[12]; }stuMsg; stuMsg students[3]; 最终需要以fwrite函数将保存了学生信息的结构体数组写入到二进制文件class.dat中。 【输入形式】 一共三行,每行依次由学生姓名,学生地址,学生电话号码组成,以空格隔开。 【输出形式】 输出该结构体到二进制文件class.dat中
时间: 2024-03-23 18:39:39 浏览: 15
以下是实现该功能的代码,可以直接运行:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct studentMessage {
char name[20];
char address[30];
char phone[12];
} stuMsg;
int main() {
stuMsg students[3];
// 读入学生信息
for (int i = 0; i < 3; i++) {
scanf("%s %s %s", students[i].name, students[i].address, students[i].phone);
}
// 打开二进制文件
FILE* fp = fopen("class.dat", "wb");
if (fp == NULL) {
printf("Failed to open file.\n");
return 0;
}
// 写入学生信息到文件中
fwrite(students, sizeof(stuMsg), 3, fp);
// 关闭文件
fclose(fp);
return 0;
}
```
首先定义了一个名为`stuMsg`的结构体,包含学生的姓名、地址和电话号码。然后在`main()`函数中定义了一个结构体数组`students`,存储三个学生的信息。
通过`scanf()`函数读入三个学生的信息,并将其存储在结构体数组中。
接着使用`fopen()`函数打开名为`class.dat`的二进制文件,如果打开失败则输出错误信息并退出程序。如果成功打开文件,则使用`fwrite()`函数将存储了学生信息的结构体数组写入到文件中。最后使用`fclose()`函数关闭文件。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![exe](https://img-home.csdnimg.cn/images/20210720083343.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)