C语言实现读取链表数据存储在文件fee.dat中
时间: 2024-03-02 13:53:36 浏览: 21
实现读取链表数据并存储在文件fee.dat中,可以按照以下步骤进行:
1. 创建链表结构体和节点结构体,如下所示:
```c
struct node {
int data;
struct node* next;
};
struct list {
struct node* head;
struct node* tail;
};
```
2. 定义文件指针,并打开文件:
```c
FILE* fp;
fp = fopen("fee.dat", "rb");
```
3. 创建一个空链表:
```c
struct list mylist;
mylist.head = NULL;
mylist.tail = NULL;
```
4. 读取文件中的数据,并将数据存储在链表中:
```c
while (fread(&data, sizeof(int), 1, fp) == 1) {
struct node* new_node = (struct node*)malloc(sizeof(struct node));
new_node->data = data;
new_node->next = NULL;
if (mylist.head == NULL) {
mylist.head = new_node;
mylist.tail = new_node;
} else {
mylist.tail->next = new_node;
mylist.tail = new_node;
}
}
```
5. 关闭文件:
```c
fclose(fp);
```
完整代码如下所示:
```c
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node* next;
};
struct list {
struct node* head;
struct node* tail;
};
int main() {
FILE* fp;
fp = fopen("fee.dat", "rb");
if (fp == NULL) {
printf("Failed to open file.\n");
return 0;
}
struct list mylist;
mylist.head = NULL;
mylist.tail = NULL;
int data;
while (fread(&data, sizeof(int), 1, fp) == 1) {
struct node* new_node = (struct node*)malloc(sizeof(struct node));
new_node->data = data;
new_node->next = NULL;
if (mylist.head == NULL) {
mylist.head = new_node;
mylist.tail = new_node;
} else {
mylist.tail->next = new_node;
mylist.tail = new_node;
}
}
fclose(fp);
return 0;
}
```