编写链表,链表里面随便搞点数据,使用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 3
saveToFile(head, "list.txt"); // 将链表数据保存到文件
head = loadFromFile(head, "list.txt"); // 从文件读取数据并添加到链表
printList(head); // 输出: 1 2 3
return 0;
}