c语言文件读取到结构体。。

c语言文件读取到结构体。。,第1张

给你个例子,这是我以前写的。

//*****************************

typedef

struct

student

/*定义数据结构*/

{

int

num

char

name[11]

int

score[4]

struct

student

*next

}lklist

//*******************************

int

read_f(lklist

*head)

/*

没有数据则返回0,有数据则返回1

*/

{

lklist

*temp,*p=head

FILE

*stu_f

if((stu_f=fopen("student.dat","rb+"))==NULL)

{

return(0)

}

else

{

temp=(lklist

*)malloc(sizeof(lklist))

while(fscanf(stu_f,"%5d%11s%6d%6d%6d%6d",&temp->num,temp->name,&temp->score[0],&temp->score[1],&temp->score[2],&temp->score[3])!=EOF)

{

p->next=temp

temp->next=NULL

p=temp

temp=(lklist

*)malloc(sizeof(lklist))

}

fclose(stu_f)

free(temp)

return(1)

}

}

//*******************************

int

save_f(lklist

*head)

/*

head为头指针储存失败返回0,成功返回1

*/

{

lklist

*temp

FILE

*stu_f

if((stu_f=fopen("student.dat","wb+"))==NULL)

{

return(0)

}

else

{

temp=head->next

while(temp!=NULL)

{

fprintf(stu_f,"%5d%11s%6d%6d%6d%6d",temp->num,temp->name,temp->score[0],temp->score[1],temp->score[2],temp->score[3])

temp=temp->next

}

fclose(stu_f)

return(1)

}

}

while(!feof(fp)) { //从文件中读取数据到结构体

fscanf(fp,"%s%d%s%d%d",stu[i].name,&stu[i].num,&stu[i].sex,stu[i].classes,

&stu[i].score[0],&stu[i].score[1])

i++

}

information.txt格式:

小红

2014003

一班

99

100

//

数据间用空格隔开

...............................................

void load( STU &head )

{

STU p, r

FILE * f

p = head

f = fopen( "1.txt", "rb" )

//隐患一:fopen一定会成功吗?,如果不成功,则,后面的 *** 作一定会出内存错误

while( !feof(f) )

{

r = (STU)malloc(sizeof(STUS))

fscanf( f, "%s", r->name )

r->next = NULL

//以下的链表赋值是无效 *** 作,建不成链表表

p = r

p = p->next

}

fclose(f)

}

修改后的load函数

void load( STU &head )

{

STU p, r

FILE * f

p = head

f = fopen( "1.txt", "rb" )

if ( !f )

{

printf("open file error\n")

return

}

while( !feof(f) )

{

r = (STU)malloc(sizeof(STUS))

fscanf( f, "%s", r->name )

r->next = NULL

if ( !head ) //如果是第一次,则记录head的位置和当前表尾p

{

head=p=r

}

else //否则,将结点r追加到表尾,并将当前结点r作为新的表尾

{

p->next=r

p=r

}

}

fclose(f)

}


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/tougao/11717493.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-18
下一篇 2023-05-18

发表评论

登录后才能评论

评论列表(0条)

保存