C语言链表读取文件函数:readFile() 实现详解
以下是一个简单的 C 语言函数示例,用于读取文件并将数据存储在链表中:
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node;
Node* readFile(const char* filename) {
FILE* file = fopen(filename, 'r');
if (file == NULL) {
printf("无法打开文件 %s\n", filename);
return NULL;
}
Node* head = NULL;
Node* tail = NULL;
int value;
while (fscanf(file, "%d", &value) == 1) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = value;
newNode->next = NULL;
if (head == NULL) {
head = newNode;
tail = newNode;
} else {
tail->next = newNode;
tail = newNode;
}
}
fclose(file);
return head;
}
int main() {
const char* filename = "input.txt";
Node* head = readFile(filename);
// 打印链表
Node* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
// 释放内存
current = head;
while (current != NULL) {
Node* temp = current;
current = current->next;
free(temp);
}
return 0;
}
在这个示例中,readFile 函数会打开指定的文件,并逐行读取文件中的整数。它会创建一个新的节点来存储每个整数,并将节点连接成一个链表。最后,它会返回链表的头节点。
在 main 函数中,我们调用 readFile 函数来读取文件,并使用一个循环打印链表中的元素。最后,我们使用另一个循环释放链表节点的内存。
请注意,这只是一个简单的示例,可能不适用于所有情况。例如,它假设文件中只包含整数,并且每个整数都在一行上。在实际应用中,您可能需要根据文件的格式和内容对代码进行修改。
原文地址: https://www.cveoy.top/t/topic/piom 著作权归作者所有。请勿转载和采集!