定义一个学生(Student)结构体类型,学号num, 姓名name, 性别sex, 年龄age, //采用fputs和fgets函数将信息写入到student.dat文件中,然后读取文件在屏幕中显示出来。(PPT32) //代码如下: //1、定义结构体Student //2、定义结构体变量 //3、给结构体变量赋值 //4、利用fputs把结构体变量的内容写入到student.dat //5、利用fgets把student.dat的内容读取出来
时间: 2023-08-14 08:06:08 浏览: 187
好的,我会根据您的要求进行回答。以下是实现您所需的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//1.定义结构体Student
typedef struct {
char num[20];
char name[20];
char sex[10];
int age;
} Student;
int main() {
//2.定义结构体变量
Student stu;
char filename[] = "student.dat";
FILE *fp;
//3.给结构体变量赋值
strcpy(stu.num, "2021001");
strcpy(stu.name, "Tom");
strcpy(stu.sex, "male");
stu.age = 20;
//4.利用fputs把结构体变量的内容写入到student.dat
fp = fopen(filename, "w");
if (fp == NULL) {
printf("Cannot open file %s!\n", filename);
exit(1);
}
fputs(stu.num, fp);
fputs("\n", fp);
fputs(stu.name, fp);
fputs("\n", fp);
fputs(stu.sex, fp);
fputs("\n", fp);
fprintf(fp, "%d\n", stu.age);
fclose(fp);
//5.利用fgets把student.dat的内容读取出来
fp = fopen(filename, "r");
if (fp == NULL) {
printf("Cannot open file %s!\n", filename);
exit(1);
}
fgets(stu.num, sizeof(stu.num), fp);
fgets(stu.name, sizeof(stu.name), fp);
fgets(stu.sex, sizeof(stu.sex), fp);
fscanf(fp, "%d", &stu.age);
fclose(fp);
//6.在屏幕中显示出读取的结构体变量的内容
printf("num: %s", stu.num);
printf("name: %s", stu.name);
printf("sex: %s", stu.sex);
printf("age: %d", stu.age);
return 0;
}
```
注:以上代码仅供参考,您可以根据实际情况进行修改。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.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)