要从文件读取数据到链表,需要按照以下步骤进行操作:
- 打开文件:使用
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 = https://www.yisu.com/ask/num;>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#include 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 = https://www.yisu.com/ask/num;>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
应为待读取的文件名,需要根据实际情况进行修改。另外,为了确保内存的释放,需要遍历链表并逐个释放节点的内存空间。