从链表中读取文件和写文件

来源:互联网 发布:新手如何修眉 知乎 编辑:程序博客网 时间:2024/05/02 04:23

#ifndef __1_H_
#define __1_H_


#define SIZE (sizeof(struct tongxun)/sizeof(char))
typedef struct tongxun
{
char id[20];
char name[30];
long num;
char zhuzhi[100];
long tel;
struct tongxun * next;
}T;


void caidan();


T * create();




T * create()

{
FILE* fp;




T* head;
head=(T*)malloc(SIZE);
if(head==NULL)
{
printf("error\n");
return NULL;
}
head->next=NULL;


fp=fopen("1","r");
if(fp==NULL)
{
printf("open error\n");
return NULL;
}
T t;
T *p,*p1;
int n;
fread(&n,sizeof(int),1,fp);
count11=n;


int i;
for(i=0;i<n;i++)
{
fread(&t,sizeof(T),1,fp);
p1=head;
while(p1->next)
{
p1=p1->next;
}
p=(T*)malloc(sizeof(T));
p->next=NULL;
strcpy(p->id,t.id);
strcpy(p->name,t.name);
strcpy(p->zhuzhi,t.zhuzhi);
p->num=t.num;
p->tel=t.tel;
p1->next=p;


}
fclose(fp);
return head;

}


void baocun(T *head){FILE *fp;fp=fopen("1","w+");if(fp==NULL){printf("open error\n");return;}fwrite(&count11,sizeof(int),1,fp);T* p;p=head;if(p->next==NULL){printf("无人,不需写入\n");fclose(fp);return ;}p=p->next;while(p){fwrite(p,sizeof(T),1,fp);p=p->next;}printf("保存成功\n");fclose(fp);}