请你编写一个程序完成将三位学生信息写入二进制文件class.dat的功能,学生信息由键盘读入,存储在一个结构体数组中。 该结构体数组的定义如下: typedef struct studentMessage { char name[20]; char address[30]; char phone[12]; }stuMsg; stuMsg students[3]; 最终需要以fwrite函数将保存了学生信息的结构体数组写入到二进制文件class.dat中。
时间: 2024-03-22 22:36:59 浏览: 78
以下是C语言编写的程序,可以将三位学生信息写入二进制文件class.dat:
```c
#include <stdio.h>
#include <stdlib.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++) {
printf("Please enter the information of student %d:\n", i + 1);
printf("Name: ");
scanf("%s", students[i].name);
printf("Address: ");
scanf("%s", students[i].address);
printf("Phone: ");
scanf("%s", 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);
printf("Successfully saved student information.\n");
return 0;
}
```
该程序首先定义了一个名为stuMsg的结构体,包含了学生的姓名、地址和电话号码三个成员变量。然后定义了一个长度为3的stuMsg类型的结构体数组students。
接着使用for循环,依次读入三位学生的信息,包括姓名、地址和电话号码,并存储到结构体数组students中。
然后使用fopen函数打开名为"class.dat"的二进制文件,如果打开文件失败则输出提示信息并结束程序。如果成功打开文件,则使用fwrite函数将保存了学生信息的结构体数组students写入到文件中。
最后使用fclose函数关闭文件,输出成功保存学生信息的提示信息,并正常结束程序。
阅读全文