|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define LEN sizeof(struct student)
struct student{
int num;//学号
char name[50];//名字
float math_score;//数学成绩
float English_score;//英语成绩
float computer_score;//计算机导论与程序设计成绩
};
int main()
{
FILE *fp;
struct student *student_write,*student_read;
//为结构体分配堆内存空间
student_write=(struct student*)malloc(LEN);
student_read=(struct student*)malloc(LEN);
if(student_write==NULL||student_read==NULL)
{
printf("内存分配失败\n");
exit(EXIT_SUCCESS);
}
//填充结构体数据
printf("请输入学生的学号,名字,数学成绩,英语成绩,计算机导论与程序设计成绩\n");
scanf("%d %s %f %f %f",&student_write->num,&student_write->name,
&student_write->math_score,&student_write->English_score,&student_write->computer_score);
//打开文件
if((fp=fopen("file.txt","w"))==NULL)
{
printf("打开文件失败!\n");
exit(EXIT_SUCCESS);
}
//将整个结构体写入文件中
fwrite(student_write,sizeof(LEN),1,fp);
//写入完成,关闭保存文件
fclose(fp);
//重新打开文件,检测是否成功写入数据
if((fp=fopen("file.txt","r"))==NULL)
{
printf("打开文件失败!\n");
exit(EXIT_FAILURE);
}
//在文件中读取结构体并打印到屏幕上
fread(student_read,sizeof(LEN),1,fp);
printf("学号:%d\n",student_read->num);
printf("姓名:%s\n",student_read->name);
printf("数学成绩:%f\n",student_read->math_score);
printf("英语成绩:%f\n",student_read->English_score);
printf("计算机导论与程序设计成绩:%f\n",student_read->computer_score);
fclose(fp);
return 0;
}
为什么会输出这么一堆玩意儿啊???
求助
本帖最后由 jackz007 于 2020-12-13 15:21 编辑 scanf("%d %s %f %f %f",&student_write->num,&student_write->name,
&student_write->math_score,&student_write->English_score,&student_write->computer_score);
改为
scanf("%d %s %f %f %f",&student_write->num,student_write->name,
&student_write->math_score,&student_write->English_score,&student_write->computer_score);
fwrite(student_write,sizeof(LEN),1,fp);
改为
fwrite(student_write,LEN,1,fp);
fread(student_read,sizeof(LEN),1,fp);
改为
fread(student_read,LEN,1,fp);
|
-
|