c语言利用子函数读取链表文件并显示
时间: 2023-08-18 18:08:42 浏览: 40
假设链表节点的结构体为:
```c
typedef struct node {
int data;
struct node *next;
} Node;
```
则可以定义一个读取链表文件的子函数如下:
```c
void readListFromFile(Node **head, char *filename) {
FILE *fp = fopen(filename, "r");
if (fp == NULL) {
printf("Failed to open file!\n");
return;
}
int data;
Node *tail = NULL;
while (fscanf(fp, "%d", &data) != EOF) {
Node *node = (Node *)malloc(sizeof(Node));
node->data = data;
node->next = NULL;
if (*head == NULL) {
*head = node;
tail = node;
} else {
tail->next = node;
tail = node;
}
}
fclose(fp);
}
```
该函数首先打开指定的文件,然后读取文件中的数据并逐一创建链表节点,将节点接入链表中。最后关闭文件。调用该函数时需要传入一个指向链表头节点指针的指针和文件名。例如:
```c
int main() {
Node *head = NULL;
readListFromFile(&head, "list.txt");
Node *p = head;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
return 0;
}
```
该程序会读取名为 `list.txt` 的文件中的数据,创建链表并打印出链表中的数据。