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

1111
2023/11/19 15:07:03
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

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

  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的文件中。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: c语言如何用指针调用函数