C语言链表(带头节点的链表)的文件读写与销毁

来源:互联网 发布:百度云计算招聘 编辑:程序博客网 时间:2024/05/20 23:07

链表的写入文件

/*====================存储彩票信息========================*//*功能:将彩票的全部数据写入文件*参数:彩票数据链表*返回值:布尔类型,读出成功返回TRUE,否则返回FALSE*/boolean writeLotteryInfo(LOTTERY *head){FILE *fp;LOTTERY *current;boolean success=FALSE;current=head->next;if(current==NULL){return FALSE;}if((fp=fopen("lotteryinfo.txt","wb+"))==NULL){printf("打开文件出现错误。\n");exit(1);}while(current!=NULL){if(fwrite(current,LOT_LEN,1,fp)==1){success=TRUE;current=current->next;}}fclose(fp);return success;}

从文件读出链表数据

/*====================读取彩票信息========================*//*功能:从文件里读出彩票的全部数据*参数:彩票数据链表*返回值:布尔类型,读出成功返回TRUE,否则返回FALSE*/boolean readLotteryInfo(LOTTERY *head){FILE *fp;LOTTERY *new_lottery,*current;boolean success=FALSE;current=head;if((fp=fopen("lotteryinfo.txt","rb+"))==NULL){printf("打开文件出现错误。\n");exit(1);}while(!feof(fp)){new_lottery=(LOTTERY *)malloc(LOT_LEN);if(new_lottery==NULL){printf("分配内存出现错误。\n");exit(1);}memset(new_lottery,'\0',LOT_LEN);if(fread(new_lottery,LOT_LEN,1,fp)==1){success=TRUE;current->next=new_lottery;current=new_lottery;}}fclose(fp);return success;}

链表的销毁

/*====================销毁彩票信息链表====================*//*功能:将全部彩票的数据的链表销毁*参数:彩票数据链表*返回值:布尔类型,读出成功返回TRUE,否则返回FALSE*/boolean destroyLotteryLink(LOTTERY *head){LOTTERY *current;boolean success=FALSE;if(head->next==NULL){success=TRUE;}else{current=head->next;while(current!=NULL){head->next=current->next;free(current);current=NULL;current=head->next;}success=TRUE;}return success;}