C语言

    技术2025-03-14  26

    /* 本程序练习链表数据结构的保存数据到文件和从文件读取数据的操作 */ #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%s\n", __FILE__, __LINE__, __func__); return; } //打开文件 FILE* fp = fopen(PATH, "rb"); if (fp == NULL) { printf("打开文件失败\n"); return; } //读取操作 MyData data; memset(&data, 0, sizeof(MyData)); int ret = 0; MyList* node = NULL; while (1) { ret = fread(&data, sizeof(MyData), 1, fp); node = createNodeLink(data);//创造节点,这里省略实现 //异常处理 if (ret == 0) { free(node); node = NULL; if (feof(fp)) { break; } else if (ferror(fp)) { fclose(fp); fp = NULL; printf("读取文件失败\n"); return; } } //插入 insertNodeLink(head, node); } //收尾处理 fclose(fp); fp = NULL; } int main(int argc, char** argv) { return 0; }

     

    Processed: 0.010, SQL: 9