本文主要是介绍C语言链表(带头节点的链表)的文件读写与销毁,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
链表的写入文件
/*====================存储彩票信息========================*/
/*功能:将彩票的全部数据写入文件
*参数:彩票数据链表
*返回值:布尔类型,读出成功返回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;
}
这篇关于C语言链表(带头节点的链表)的文件读写与销毁的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!