温馨提示×

c语言如何把链表与文件结合

小亿
80
2023-12-07 04:39:46
栏目: 编程语言

在C语言中,可以通过文件操作函数将链表与文件结合起来。具体步骤如下:

  1. 定义链表的结构体
typedef struct Node {
    int data;
    struct Node* next;
} Node;
  1. 实现链表的插入、删除等操作函数
Node* insert(Node* head, int data) {
    Node* newNode = (Node*)malloc(sizeof(Node));
    newNode->data = data;
    newNode->next = NULL;

    if (head == NULL) {
        head = newNode;
    } else {
        Node* temp = head;
        while (temp->next != NULL) {
            temp = temp->next;
        }
        temp->next = newNode;
    }

    return head;
}

Node* delete(Node* head, int data) {
    Node* current = head;
    Node* prev = NULL;

    while (current != NULL) {
        if (current->data == data) {
            if (prev == NULL) { // 删除头节点
                head = current->next;
            } else {
                prev->next = current->next;
            }
            free(current);
            break;
        }

        prev = current;
        current = current->next;
    }

    return head;
}
  1. 实现将链表数据写入文件的函数
void writeToFile(Node* head, const char* filename) {
    FILE* file = fopen(filename, "w");
    if (file == NULL) {
        printf("Failed to open file!\n");
        return;
    }

    Node* current = head;
    while (current != NULL) {
        fprintf(file, "%d\n", current->data);
        current = current->next;
    }

    fclose(file);
}
  1. 实现从文件中读取数据到链表的函数
Node* readFromFile(const char* filename) {
    FILE* file = fopen(filename, "r");
    if (file == NULL) {
        printf("Failed to open file!\n");
        return NULL;
    }

    Node* head = NULL;
    int data;
    while (fscanf(file, "%d", &data) != EOF) {
        head = insert(head, data);
    }

    fclose(file);
    return head;
}

这样,就可以通过调用这些函数,将链表中的数据写入文件,或者从文件中读取数据到链表中。例如:

int main() {
    Node* head = NULL;

    // 插入数据到链表中
    head = insert(head, 1);
    head = insert(head, 2);
    head = insert(head, 3);

    // 将链表中的数据写入文件
    writeToFile(head, "data.txt");

    // 从文件中读取数据到链表
    Node* newHead = readFromFile("data.txt");

    // 打印链表中的数据
    Node* current = newHead;
    while (current != NULL) {
        printf("%d ", current->data);
        current = current->next;
    }

    // 释放链表内存
    while (newHead != NULL) {
        Node* temp = newHead;
        newHead = newHead->next;
        free(temp);
    }

    return 0;
}

0