用fwrite将文件写入后,想用fread读取文件出现问题 - 爱问答

(爱问答)

用fwrite将文件写入后,想用fread读取文件出现问题

#include<stdio.h>

#include<stdlib.h>

struct stud_record{

long no;

int age;

float score;

};

struct stud_node{

struct stud_record stud_member;

struct stud_node *next;

};

#define LEN sizeof(struct stud_node)

struct stud_node* create(){

struct stud_node *head,*p,*q;

long no;

int age;

float score;

head=NULL;

while(1){

printf("请输入学生记录(学号,年龄,入学成绩): ");

scanf("%ld%d%f",&no,&age,&score);

//printf("%ld ",no);

if(no<0)

break;

p=(struct stud_node*)malloc(LEN);

p->stud_member.no=no;

p->stud_member.age=age;

p->stud_member.score=score;

if(head==NULL)

head=p;

else

q->next=p;

q=p;

}

if(head!=NULL)

q->next=NULL;

return head;

}

int main(){

FILE *fp;

if((fp=fopen("c:users杨柳desktopdate.rec","wb"))==NULL){

printf("无法创建文件!");

exit(0);

}

struct stud_node *p,*q;

struct stud_node *head,*x,*y;//x用来存放新申请的结点指针

p=q=create(); //y用来存放新申请结点的直接前驱结点指针

while(p!=NULL){

fwrite(&(p->stud_member),sizeof(p->stud_member),1,fp);

//printf("%ld %d %f ",p->stud_member.no,p->stud_member.age,p->stud_member.score);

q=p;

p=q->next;

}

 

rewind(fp);

while(fread(&(x->stud_member),sizeof(x->stud_member),1,fp)==1){

printf("** ");

printf("%ld %d %f ",x->stud_member.no,x->stud_member.age,x->stud_member.score);

}

/*head=NULL;

rewind(fp);

while(fread(&stud,LEN,1,fp)==1){

printf("%ld %d %f ",x->stud_member.no,x->stud_member.age,x->stud_member.score);

if(head==NULL)

head=x;

else

y->next=x;

y=x;

}

if(head!=NULL)

y->next=NULL;*/

 

return 0;

}


程序看上去逻辑很乱

首先(最大的问题)

你的文件是用"wb"方式打开的,它就只能写不能读的,你freadi当然不可能读到内容的

要改写文件,能读写,应该用r+b

其次,你的x没有申请内存你就使用它,也要出错的

下一篇:c语言if语句应用的多吗?

上一篇:wps2019的开发工具在哪

热门标签:
excel 网盘 破解 word dll
最新更新:
微软重新评估新的Outlook的使用时机 联想推出搭载联发科Helio G80芯片组的Tab M9平板 英特尔创新大赛时间确定! 微软Edge浏览器在稳定渠道中推出Workspaces功能 英伟达RTX4060TiGPU推出MaxSun动漫主题! 谷歌地图为用户提供了街景服务! GameSir 在T4 Kaleid中推出了一款出色的控制器! 微软开始在Windows 11 中测试其画图应用程序的新深色模式! LG电子推出全球首款无线OLED电视 英伟达人工智能芯片崭露头角! Steam Deck可以玩什么游戏-Steam Deck价格限时优惠 雷蛇推出CobraPro鼠标 Kindle电子阅读器可以访问谷歌商店吗 Windows10如何加入组策略 window10图片查看器怎么没有了?