溫馨提示×

c語言如何將鏈表內容輸入到文件中

小億
390
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
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女