从键盘输入两个学生数据,写入一个文件,再读取出这两个学生数据显示在屏幕
时间: 2024-04-04 11:36:11 浏览: 33
以下是一个简单的C语言程序,可以实现该功能:
```c
#include <stdio.h>
struct student {
char name[20];
int age;
float score;
};
int main() {
struct student stu1, stu2;
FILE *fp;
// 从键盘输入两个学生数据
printf("请输入第一个学生的姓名、年龄、成绩:");
scanf("%s %d %f", stu1.name, &stu1.age, &stu1.score);
printf("请输入第二个学生的姓名、年龄、成绩:");
scanf("%s %d %f", stu2.name, &stu2.age, &stu2.score);
// 将学生数据写入文件
fp = fopen("students.dat", "wb");
fwrite(&stu1, sizeof(struct student), 1, fp);
fwrite(&stu2, sizeof(struct student), 1, fp);
fclose(fp);
// 从文件中读取学生数据并显示在屏幕
fp = fopen("students.dat", "rb");
fread(&stu1, sizeof(struct student), 1, fp);
fread(&stu2, sizeof(struct student), 1, fp);
printf("\n从文件中读取的两个学生数据为:\n");
printf("%s %d %.2f\n", stu1.name, stu1.age, stu1.score);
printf("%s %d %.2f\n", stu2.name, stu2.age, stu2.score);
fclose(fp);
return 0;
}
```
在上面的程序中,我们先定义了一个结构体 `student`,表示学生数据的类型,包含学生姓名、年龄和成绩。然后在主函数中,先从键盘输入两个学生数据,再将这两个学生数据写入文件 "students.dat",最后从文件中读取学生数据并显示在屏幕上。注意,在写文件时要以二进制方式打开文件,以保证数据的正确性。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)