C编程问题,链表

来源:百度知道 编辑:UC知道 时间:2024/06/30 02:17:30
#include<malloc.h>
#define LEN sizeof(struct memory)
struct memory
{
char name[10];
char sex[4];
struct memory *next;
};
void main()
{
int i,j;
struct memory*head,*p;
FILE *fp;
if((fp=fopen("D:\\data.txt","rb"))==NULL)
{
printf("cannont open ");
return;
}
head=0;
for(i=0;i<9;i++)
{
p=(struct memory *) malloc(LEN);
p->next=head;
head=p;
fread(&p,sizeof(struct memory),1,fp); /*问题*/
}
for(p=head;p;p=p->next)
{
printf("%s %s\n",p->name,p->sex);
}
}
D盘下的data.txt里面数据时:
mihairen man qinshou man luoxiang man
怎么不能运行?

#include<stdio.h>
#include<malloc.h>
#define LEN sizeof(struct memory)
struct memory
{
char name[10];
char sex[4];
struct memory *p;
};
void main()
{
int i,j;
struct memory*head,*p;
FILE *fp;
if((fp=fopen("D:\\data.txt","rb"))==NULL)
{printf("cannont open ");
return;}
for(i=0;i<9;i++)
{head=p=(struct memory *) malloc(LEN);
printf("请键入:");
scanf("%s%s",&p->name,&p->sex);
fread(p,sizeof(struct memory),1,fp);
printf("%-10s%-8s\n",p->name,p->sex);
printf("------------------------------------------\n");
p=p->p;}

}

当然不用直接只用一个fread读啊,因为考虑到字节对齐的情况,你从文件中读到的数据不可能正好赋给相应的成员.要一个成员一个成员的读