如何写一个链接列表对象到一个文件 [英] How to write a linked list object to a file

查看:147
本文介绍了如何写一个链接列表对象到一个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  void writeFile(){
Employer * temp = head;
while(temp!= NULL)
{
temp-> tryWrite(); //这里调用的Employee的显示方法
temp = temp-> getNext();


$ b $ void main(){
EmployerList em;
em.AddNode(des@yahoo.com,LIME,Manager,ming,ding,Newston,43,873);
em.AddNode(sw@gmail.com,NOKIA,CEO,rew,nbv,Europe,0411-789-6548,985-257-1111 );
//em.writeFile();





$ b我试图将链接列表写入文件作为对象而不是奇怪就像我在tryWrite函数中。任何帮助?

解决方案

简短的回答是不,你不能这样做。 b

一个链表,几乎按照定义,包含指针。至少对于长期存储(即任何在单个程序执行之外存活的东西),通过存储一个指向磁盘的指针,然后再读回来,你不能得到任何有意义的东西。

序列化包含指针的数据结构通常需要追逐这些指针,并以某种方式扁平化结构。对于线性链表,您可能只是想按顺序编写节点。另一种可能是将文件中的偏移量替换为内存的指针。如果您需要在磁盘上维护相同类型的结构(例如,您需要一个可以在磁盘上作为实际树来操作的树,而不仅仅是一系列记录),那么这将非常有用。



无论如何,只要存储原始数据不太可能有用。


void writeFile(){
    Employer *temp = head;
    while (temp != NULL)
    {
        temp->tryWrite();//Employee's display method called here
        temp = temp->getNext();
    }
}

void main(){
    EmployerList em;
    em.AddNode("des@yahoo.com", "LIME", "Manager", "ming", "ding", "Newston", "43", "873");
    em.AddNode("sw@gmail.com", "NOKIA", "CEO", "rew", "nbv", "Europe", "0411-789-6548", "985-257-1111"); 
    //em.writeFile();
}

I am trying to write the linked list to the file as an object instead of singularly like i have in the tryWrite function. any help?

解决方案

The short answer is "No, you can't do that."

A linked list, pretty much by definition, contains pointers. At least for long-term storage (i.e., anything that survives outside a single execution of the program), you can't get anything meaningful by storing a pointer to disk, and then reading it back in.

Serializing data structures that contain pointers generally requires "chasing" those pointers, and "flattening" the structure in some way. For a linear linked list, you probably just want to write the nodes in order. Another possibility is to substitute offsets in the file for pointers to memory. That's primarily useful if you need to maintain the same type of structure on disk (e.g., you want a tree that you can manipulate on disk as an actual tree, not just a sequence of records).

Anyway you go at it, though, just storing the raw data is unlikely to be useful.

这篇关于如何写一个链接列表对象到一个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆