read+write实现:链表放到文件+文件数据放到链表 的功能

思路 

一、 定义链表:

1 节点结构(数据int型)
2 链表操作(创建节点、插入节点、释放链表、打印链表)。

二、链表保存到文件 

1打开文件
2遍历链表、写文件:
        遍历链表,write()将节点数据写入文件。
3关闭文件

三、从文件加载数据到链表

1打开文件
2读文件、建链表:
        read ()从文件读取数据,
        创建节点(放数据)。接起来,建链表。
3关闭文件  

代码: 

// 定义节点结构
typedef struct Node {
    int data;
    struct Node* next;
} Node;

// 创建节点
Node* createNode(int data) {
    Node* newNode = (Node*)malloc(sizeof(Node));
    if (newNode == NULL) {
        perror("malloc failed");
        exit(EXIT_FAILURE);
    }
    newNode->data = data;
    newNode->next = NULL;
    return newNode;
}

// 尾插
void insertNode(Node** head, int data) {
    Node* newNode = createNode(data);
    if (*head == NULL) {
        *head = newNode;
        return;
    }
    Node* t= *head;
    while (t->next != NULL) {
        t= t->next;
    }
    t->next = newNode;
}
// 释放链表
void freeList(Node* head) {
    Node* t;
    while (head != NULL) {
        t= head;
        head = head->next;
        free(t);
    }
}

// 打印链表
void printList(Node* head) {
    Node* t= head;
    while (t!= NULL) {
        printf("%d ", t->data);
        t= t->next;
    }
    printf("\n");
}

// 链表保存到文件
void saveListToFile(Node* head, const char* filename) {
    int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666);

    Node *t= head;
    while (t!= NULL) {
        if (write(fd, &t->data, sizeof(int)) != sizeof(int)) {
            perror("write failed");
            close(fd);
            exit(EXIT_FAILURE);
        }
        t= t->next;
    }
    close(fd);
}

// 从文件加载到链表
Node* loadListFromFile(const char* filename) {
    int fd = open(filename, O_RDONLY);

    Node *head = NULL;
    Node *tail = NULL;
    int data;

    while (read(fd, &data, sizeof(data)) == sizeof(data)) {
        Node *newNode = createNode(data);
        if (head == NULL) {
            head = newNode;
            tail = newNode;
        } else {
            tail->next = newNode;
            tail = newNode;
        }
    }

    close(fd);
    return head;
}

int main(int argc, const char *argv[])
{
    // 创建链表
	Node* head = NULL;
    insertNode(&head, 11);
    insertNode(&head, 22);
    insertNode(&head, 33);
    // 打印链表
    printf("原链表: ");
    printList(head);

    // 保存链表到文件
    saveListToFile(head, "list_data.txt");

    // 释放链表
    freeList(head);

    // 从文件加载到链表
    head = loadListFromFile("list_data.txt");

    // 打印链表
    printf("加载后的链表: ");
    printList(head);

    // 释放链表
    freeList(head);

	return 0;
}

运行结果 

 read+write实现:链表放到文件+文件数据放到链表 的功能_第1张图片

你可能感兴趣的:(链表,数据结构,算法)