请使用read 和 write 实现链表保存到文件,以及从文件加载数据到链表中的功能
link.h
#ifndef __link__
#define __link__#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <pthread.h>
#include <semaphore.h>
#include <wait.h>
#include <signal.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <semaphore.h>
#include <sys/msg.h>
#include <sys/shm.h>
#include <sys/un.h>typedef struct node
{union{int len;char arr[10];};struct node* next;
}linklist,*linkptr;linkptr create();int add(linkptr p,char* brr);void seav(linkptr p,char *filename);void load(linkptr p,char *filename);#endif
link.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>typedef struct linklist {char arr[10];struct linklist *next;int len;
} linklist;typedef linklist *linkptr;// 创建链表
linkptr create() {linkptr p = (linkptr)malloc(sizeof(linklist));if (NULL == p) {printf("创建失败\n");return NULL;}p->len = 0;p->next = NULL;return p;
}// 添加节点
int add(linkptr p, char *brr) {if (NULL == p) {printf("增加失败\n");return 0;}linkptr e = (linkptr)malloc(sizeof(linklist));if (NULL == e) {printf("内存分配失败\n");return 0;}strcpy(e->arr, brr);e->next = p->next;p->next = e;p->len++;return 1;
}// 保存链表到文件
void save(linkptr h, char *filename) {if (NULL == h) {printf("写入文件失败\n");return;}FILE *fp = fopen(filename, "w");if (fp == NULL) {perror("fopen");return;}linkptr p = h->next;while (p != NULL) {fprintf(fp, "%s\n", p->arr);p = p->next;}fclose(fp);
}// 从文件加载链表
void load(linkptr h, char *filename) {if (NULL == h) {printf("载入失败\n");return;}FILE *fp = fopen(filename, "r");if (fp == NULL) {perror("fopen");return;}while (1) {char brr[11] = {0}; // 确保有足够的空间存储字符串和结束符if (fgets(brr, sizeof(brr), fp) == NULL) {break;}brr[strcspn(brr, "\n")] = '\0'; // 移除换行符add(h, brr);}fclose(fp);
}
main.c
#include"link.h"int main(){linkptr l=create();add(l,"zzy");add(l,"hqyj");add(l,"666");seav(6,"1.txt");linkptr l2=create();load(l2,"1.txt");return 0;
}