/*
本程序练习链表数据结构的保存数据到文件和从文件读取数据的操作
*/
#include<stdio.h>
#include<string.h>
#define PATH "data_link.dat"//文件保存路径
//定义一个数据结构体
typedef struct MyData
{
int a_data;
char c_data;
}MyData;
//根据数据结构体定义链表的结构体
typedef struct MyList
{
MyData data;
struct MyList* next;
}MyList;
/*
函数名:storeListFile
函数功能:保存链表数据到文件
返回值:void
参数列表:MyList* head
参数说明:
head:要保存链表数据的头结点
*/
void storeListFile(MyList* head)
{
//异常预处理
if (head == NULL)
{
printf("节点为空,保存失败\n%s\t%d\t%s\n", __FILE__, __LINE__, __func__);
return;
}
//打开文件
FILE* fp = fopen(PATH, "wb");
if (fp == NULL)
{
printf("打开文件失败\n");
return;
}
//保存操作
MyList* p = head->next;
while (p != NULL)
{
fwrite(&p->data, sizeof(MyData), 1, fp);
p = p->next;
}
//收尾处理
fclose(fp);
fp = NULL;
}
/*
函数名:readListFile
函数功能:从文件读取链表数据
返回值:void
参数列表:MyList* head
参数说明:
head:要读取链表数据的头结点
*/
void readListFile(MyList* head)
{
//异常预处理
if (head == NULL)
{
printf("节点为空,读取失败\n%s\t%d\t%
C语言_保存_读取_链表数据到文件
最新推荐文章于 2023-06-05 13:28:51 发布