C语言:将文件数据读取到链表中
以下是一个示例程序,演示如何读取文件中的数据到链表中:
#include <stdio.h>
#include <stdlib.h>
// 链表节点结构体
typedef struct Node {
int data;
struct Node* next;
} Node;
// 在链表末尾插入节点
void insertAtEnd(Node** head, int data) {
// 创建新节点
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
// 如果链表为空,则将新节点设为头节点
if (*head == NULL) {
*head = newNode;
return;
}
// 否则,找到链表的末尾节点,并将新节点插入末尾
Node* current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
// 释放链表内存
void freeList(Node** head) {
Node* current = *head;
Node* next;
while (current != NULL) {
next = current->next;
free(current);
current = next;
}
*head = NULL;
}
int main() {
FILE* file = fopen('data.txt', 'r');
if (file == NULL) {
printf('无法打开文件\n');
return 1;
}
Node* head = NULL; // 链表头节点
int num;
while (fscanf(file, '%d', &num) != EOF) {
insertAtEnd(&head, num);
}
fclose(file);
// 打印链表中的数据
Node* current = head;
while (current != NULL) {
printf('%d ', current->data);
current = current->next;
}
printf('\n');
// 释放链表内存
freeList(&head);
return 0;
}
在上面的示例程序中,首先通过 fopen 函数打开文件,如果文件打开失败,则会输出错误信息并终止程序。然后,我们定义了一个链表结构体 Node,以及几个操作链表的函数。在 main 函数中,我们首先创建了一个空链表 head,然后使用 fscanf 函数从文件中读取数据,并调用 insertAtEnd 函数将数据插入链表的末尾。最后,我们通过遍历链表并打印其中的数据,将文件中的数据输出到控制台。最后,我们调用 freeList 函数释放链表的内存。
原文地址: https://www.cveoy.top/t/topic/pjE3 著作权归作者所有。请勿转载和采集!