C言語で、リンクリストのデータをファイルに格納する方法
C言語では、ファイル操作に関する関数を用いて、リンクリストのデータをファイルに書き出すことができます。以下に簡単なサンプルコードを示します。
#include <stdio.h>
#include <stdlib.h>
// 链表节点结构定义
struct Node {
int data;
struct Node* next;
};
// 将链表中的数据存入文件
void saveListToFile(struct Node* head, const char* filename) {
// 打开文件以写入模式
FILE* file = fopen(filename, "w");
if (file == NULL) {
printf("无法打开文件!\n");
return;
}
// 遍历链表,将数据写入文件
struct Node* current = head;
while (current != NULL) {
fprintf(file, "%d\n", current->data);
current = current->next;
}
// 关闭文件
fclose(file);
}
int main() {
// 创建链表
struct Node* head = (struct Node*)malloc(sizeof(struct Node));
struct Node* second = (struct Node*)malloc(sizeof(struct Node));
struct Node* third = (struct Node*)malloc(sizeof(struct Node));
head->data = 1;
head->next = second;
second->data = 2;
second->next = third;
third->data = 3;
third->next = NULL;
// 将链表中的数据存入文件
saveListToFile(head, "data.txt");
// 释放链表内存
free(head);
free(second);
free(third);
return 0;
}
このコード例では、まず連結リストノード構造体 struct Node が定義され、整数データと次のノードを指すポインターが含まれています。次に、連結リストのヘッドノードとファイル名をパラメーターとして受け取り、ファイルを開き、連結リストを走査し、データを書き込むことで連結リストのデータをファイルに格納する saveListToFile 関数が定義されています。main 関数では、単純な連結リストが作成され、saveListToFile 関数が呼び出されて、連結リストのデータが「data.txt」という名前のファイルに格納されます。最後に、連結リストのメモリが解放されます。