链表数据存入文件
时间: 2023-09-07 16:14:28 浏览: 214
链表数据存入文件的步骤如下:
1. 打开文件:使用 fopen() 函数打开要写入的文件,可以选择以二进制或文本格式打开文件。
2. 遍历链表:使用循环遍历链表,将每个节点的数据写入文件。
3. 写入数据:使用 fwrite() 函数将节点数据写入文件中,可以使用 sizeof() 函数计算每个节点数据的大小。
4. 关闭文件:使用 fclose() 函数关闭文件。
下面是一个简单的示例代码,将链表数据存入文件中:
```c
#include <stdio.h>
struct Node {
int data;
struct Node* next;
};
void saveListToFile(struct Node* head, const char* fileName) {
FILE* fp = fopen(fileName, "wb");
if (fp == NULL) {
printf("Failed to open file.\n");
return;
}
struct Node* curr = head;
while (curr != NULL) {
fwrite(&curr->data, sizeof(int), 1, fp);
curr = curr->next;
}
fclose(fp);
}
int main() {
struct Node* head = NULL;
// 将链表数据插入到 head 中
saveListToFile(head, "list.dat");
return 0;
}
```
在上面的代码中,我们使用 fwrite() 函数将每个节点的数据写入文件中,文件以二进制格式打开。在保存链表时,我们只需要将链表的头指针传递给 saveListToFile() 函数即可。
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)