要从文件读取数据到链表,需要按照以下步骤进行操作:
fopen
函数打开文件,返回一个文件指针。FILE *fp;
fp = fopen("filename", "r");
if (fp == NULL) {
printf("文件打开失败\n");
return;
}
typedef struct Node {
int data; // 假设存储整数数据
struct Node *next;
} Node;
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
应为待读取的文件名,需要根据实际情况进行修改。另外,为了确保内存的释放,需要遍历链表并逐个释放节点的内存空间。