C语言的存储和读取功能问题

2024-12-30 07:51:23
推荐回答(3个)
回答1:

读取数据的时候,要重新建立链表结构,读一个数据,申请一个结点,再把它插入到链表中去。大概应该是下面的样子
struct worker *p, *q = NULL;
while(!feof(fp))
{
p = (struct worker*)malloc(sizeof(struct worker));
fread(p, sizeof(struct worker), 1, fp);
p->next = NULL;
if (q != NULL)
q->next = p;
q = p;
}

回答2:

有不少问题,读取的时候没有先开辟保存信息的空间;
返回的时候也没有返回读取后的head;

下面是我写的代码,已经在unix机器上测试过了,可以正常读取;

#include
#include
#define LEL sizeof(struct worker)
#define WEW 0
#define ISO "%5d%13s%8s%7d/%d/%d%10s%10s%10d%10d\n"
struct worker
{
long num; /*工号*/
char a[20]; /*姓名*/
char sex[5]; /*性别,m代表男性,f代表女性*/
int b[3]; /*出生年月日*/
char c[20]; /*学历*/
char d[20]; /*职务*/
int wages; /*工资*/
long telephone; /*电话*/
struct worker *next;
};

void output(struct worker *head) /*输出信息*/
{struct worker *p;
p=head;
do
{
printf(ISO,p->num,p->a,p->sex,p->b[0],p->b[1],p->b[2],p->c,p->d,p->wages,p->telephone);
p=p->next;
}while(p!=WEW);
}

void keep(struct worker *head) /*保存功能*/
{
FILE *fp;
struct worker *p;
char a[20];
printf("请输入文件名:");
gets(a);
gets(a);
if((fp=fopen("a","wb"))==NULL)
{
printf("此文件不存在,无法保存.\n");
}
for(p=head;p!=NULL;p=p->next)
if(fwrite(p,sizeof(struct worker),1,fp)!=1)
printf("存入出错,未保存 成功\n");
fclose(fp);
}

struct worker *read() /*读取功能*/
{
FILE *fp;
struct worker *head=NULL,*p,*q=NULL;
char a[20];
printf("请输入所需要打开文件的名称:");
gets(a);
gets(a);
if((fp=fopen("a","rb"))==NULL)
{
printf("无法打开%s文件",a);
return NULL;
}

//在这先new出空间,用来从文件流中读取数据
for(;1;)
{
//每次需要New出一个新空间用于保存读取的数据
p=(struct worker*) malloc(sizeof(struct worker));

if( fread(p,sizeof(struct worker),1,fp) != 1 )
break;

if(head==NULL)head=p;
if(q!=NULL)q->next=(struct worker*)p;//将新的空间放到链表后面
q=(struct worker*)p;
}

fclose(fp);
return head;
}

void main()
{

int m=1,wages,num,i=0;

struct worker q={1001,"zhangshan","nan",{1988,06,21},"benke","zhuguan",4000,6337877};
struct worker w={1002,"wanghua","nv",{1988,07,21},"benke","zhuguan",3000,6337887};
struct worker e={1003,"xiaoli","nan",{1977,07,21},"zhuanke","zhuguan",2000,6337889};
struct worker *head;
head=&q;
q.next=&w;
w.next=&e;
e.next=WEW;
printf("***********************************************************\n");
printf("*********************职工管理信息系统**********************\n");
printf("********************请选择以下所需功能*********************\n");
printf("********************2、输出所有职工信息********************\n");
printf("********************7、保存数据****************************\n");
printf("********************8、读取以有数据************************\n");
printf("***********************************************************\n");
printf("\n");

while(m!=0)
{
printf("***请输入所需功能所代表的数字***:");
scanf("%d",&m);
switch(m)
{
case 2:
output(head);
break;
case 7:
keep(head);
printf("数据保存成功\n");
break;
case 8:
head=read();
break;
default:
continue;
}
}

}

回答3:

给点出错信息呀。