c语言怎么从文件读取数据到链表

   2025-02-13 8940
核心提示:要从文件读取数据到链表,需要按照以下步骤进行操作:打开文件:使用fopen函数打开文件,返回一个文件指针。FILE *fp;fp = fopen

要从文件读取数据到链表,需要按照以下步骤进行操作:

打开文件:使用fopen函数打开文件,返回一个文件指针。
FILE *fp;fp = fopen("filename", "r");if (fp == NULL) {    printf("文件打开失败\n");    return;}
创建链表节点结构体:根据需要创建一个链表节点的结构体,包含需要存储的数据和指向下一个节点的指针。
typedef struct Node {    int data;  // 假设存储整数数据    struct Node *next;} Node;
定义链表头节点:创建一个指向链表头部的指针,并初始化为NULL。
Node *head = NULL;
读取文件内容:使用fscanf函数逐行读取文件内容,并将读取到的数据存储到链表节点中。
int num;while (fscanf(fp, "%d", &num) != EOF) {    // 创建新的节点并存储数据    Node *newNode = (Node*)malloc(sizeof(Node));    newNode->data = num;    newNode->next = NULL;    // 将新节点插入链表    if (head == NULL) {        head = newNode;    } else {        Node *temp = head;        while (temp->next != NULL) {            temp = temp->next;        }        temp->next = newNode;    }}
关闭文件:使用fclose函数关闭文件。
fclose(fp);

完整的代码示例:

#include <stdio.h>#include <stdlib.h>typedef struct Node {    int data;    struct Node *next;} Node;int main() {    FILE *fp;    fp = fopen("filename", "r");    if (fp == NULL) {        printf("文件打开失败\n");        return 0;    }    Node *head = NULL;    int num;    while (fscanf(fp, "%d", &num) != EOF) {        Node *newNode = (Node*)malloc(sizeof(Node));        newNode->data = num;        newNode->next = NULL;        if (head == NULL) {            head = newNode;        } else {            Node *temp = head;            while (temp->next != NULL) {                temp = temp->next;            }            temp->next = newNode;        }    }    fclose(fp);    // 遍历链表并输出    Node *temp = head;    while (temp != NULL) {        printf("%d ", temp->data);        temp = temp->next;    }    // 释放链表内存    temp = head;    while (temp != NULL) {        Node *next = temp->next;        free(temp);        temp = next;    }    return 0;}

注意:上述代码中的filename应为待读取的文件名,需要根据实际情况进行修改。另外,为了确保内存的释放,需要遍历链表并逐个释放节点的内存空间。

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言