要從文件讀取數據到鏈表,需要按照以下步驟進行操作:
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
應為待讀取的文件名,需要根據實際情況進行修改。另外,為了確保內存的釋放,需要遍歷鏈表并逐個釋放節點的內存空間。