C言語でリンクリストの中身をファイルに出力するには
次の手順に従って、ファイルにリンクされたリストの内容を入力します。
- fopen() 関数を使用してファイルを開く
FILE *file = fopen("filename.txt", "w");
- リストの操作: while または for などのループ構造を使用し、リスト内の各ノードを操作します。
- fprintf()関数を使用してノードの内容をファイルに書き込みます。次に例を示します。
fprintf(file, "%d\n", node->data);
node->data はノードで保持するデータで、%d は整数の形式で出力し、\n は改行を表します。
- fclose(filename)
fclose(file);
完全なコード例:
#include <stdio.h>
struct Node {
int data;
struct Node* next;
};
void writeLinkedListToFile(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* node1 = (struct Node*)malloc(sizeof(struct Node));
struct Node* node2 = (struct Node*)malloc(sizeof(struct Node));
struct Node* node3 = (struct Node*)malloc(sizeof(struct Node));
node1->data = 1;
node1->next = node2;
node2->data = 2;
node2->next = node3;
node3->data = 3;
node3->next = NULL;
writeLinkedListToFile(node1, "linkedlist.txt");
return 0;
}
サンプルのリストのデータ(1,2,3)をlinkedlist.txtというファイルに上記のコードによって書き込みます。