从键盘输入一名学生的信息,创建名为“stuinfo.dat”的文件,然后将这些信息保存到该文件中,最后将文件中的信息读出,显示在屏幕上。请根据提示,在指定位置上补充代码,实现程序功能。
时间: 2024-03-02 17:52:56 浏览: 27
以下是一份可能的实现代码,其中需要填充的部分用 TODO 标注:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
char name[20];
int age;
char gender[5];
} Student;
int main() {
Student stu;
FILE *fp;
// TODO: 打开名为“stuinfo.dat”的文件,以二进制写入模式打开,赋值给fp指针
printf("请输入学生姓名:");
scanf("%s", stu.name);
printf("请输入学生年龄:");
scanf("%d", &stu.age);
printf("请输入学生性别:");
scanf("%s", stu.gender);
// TODO: 将stu写入fp指向的文件中
fclose(fp);
fp = NULL;
fp = fopen("stuinfo.dat", "rb");
if (fp == NULL) {
printf("无法打开文件!");
exit(1);
}
printf("学生信息如下:\n");
while (fread(&stu, sizeof(Student), 1, fp) == 1) {
printf("姓名:%s,年龄:%d,性别:%s\n", stu.name, stu.age, stu.gender);
}
fclose(fp);
fp = NULL;
return 0;
}
```
该程序中定义了一个结构体 `Student`,包含学生的姓名、年龄和性别三个字段。程序首先通过打开文件的方式,将学生信息写入名为“stuinfo.dat”的文件中。然后再次打开该文件,通过 `fread()` 函数读取其中的学生信息,最后在屏幕上显示出来。
相关推荐
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![](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)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)