温馨提示×

c语言如何将链表内容输入到文件中

小亿
176
2023-11-22 15:07:03
栏目: 编程语言

要将链表内容输入到文件中,可以按照以下步骤进行操作:

  1. 打开文件:使用文件指针变量和fopen()函数打开一个文件。例如,可以使用以下代码将文件以写入模式打开:
FILE *file = fopen("filename.txt", "w");
  1. 遍历链表:使用循环结构(如whilefor循环)遍历链表中的每个节点。

  2. 将节点内容写入文件:使用fprintf()函数将节点内容写入文件中。例如,可以使用以下代码将节点的内容写入文件:

fprintf(file, "%d\n", node->data);

其中,node->data为节点中存储的数据,%d表示以整数形式写入,\n表示换行。

  1. 关闭文件:使用fclose()函数关闭文件,释放资源。例如,可以使用以下代码关闭文件:
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的文件中。

0