編寫鏈表,鏈表里面隨便搞點數據,使用fprintf將鏈表中所有的數據保存到文件中,用fscanf讀取文件中的數據寫入鏈表中
#include <stdio.h>
#include <stdlib.h>typedef struct Node {int data;struct Node* next;
} Node;// 創建新節點
Node* createNode(int data) {Node* newNode = (Node*)malloc(sizeof(Node));if (!newNode) {printf("Memory error\n");return NULL;}newNode->data = data;newNode->next = NULL;return newNode;
}// 添加新節點到鏈表末尾
Node* addNode(Node* head, int data) {Node* newNode = createNode(data);if (head == NULL) {head = newNode;} else {Node* temp = head;while (temp->next != NULL) {temp = temp->next;}temp->next = newNode;}return head;
}// 打印鏈表
void printList(Node* head) {Node* temp = head;while (temp != NULL) {printf("%d ", temp->data);temp = temp->next;}printf("\n");
}// 保存鏈表到文件
void saveToFile(Node* head, const char* filename) {FILE* file = fopen(filename, "w");if (file == NULL) {printf("Unable to open file for writing\n");return;}Node* temp = head;while (temp != NULL) {fprintf(file, "%d ", temp->data);temp = temp->next;}fclose(file);
}// 從文件讀取數據并添加到鏈表
Node* loadFromFile(Node* head, const char* filename) {FILE* file = fopen(filename, "r");if (file == NULL) {printf("Unable to open file for reading\n");return head;}int data;while (fscanf(file, "%d", &data) == 1) {head = addNode(head, data);}fclose(file);return head;
}int main() {Node* head = NULL;head = addNode(head, 1);head = addNode(head, 2);head = addNode(head, 3);printList(head); // 輸出: 1 2 3saveToFile(head, "list.txt"); // 將鏈表數據保存到文件head = loadFromFile(head, "list.txt"); // 從文件讀取數據并添加到鏈表printList(head); // 輸出: 1 2 3return 0;
}