在c ++中从同一个二进制文件读取和写入

时间:2013-09-25 00:27:51

标签: c++ c file-io

我正在尝试将链接列表写入二进制文件,然后在程序启动时将其读回。

我为此编写了以下代码:

class Node
{
    private:
        int pos;
        int data;
        Node* next;
        Node* prev;

        friend class Linklist;

    public:
        Node(int d):data(d),pos(-1),next(NULL),prev(NULL)
        {}  

};
#include <new>
#include <sstream>
#include<iostream>
#include"linklist.h"

bool Linklist::insert(int data, bool updateDisk)
{
    if(isExist(data))
    {
        std::cout<<"Tried to insert duplicate data";
        return false;
    }

    Node *temp  = new (std::nothrow) Node(data);
    if(temp == NULL)
    {
       return false;
    }

    if(tail == NULL)
    {
        tail = temp;
        head = temp;
    }
    else
    {
        tail->next = temp;
        temp->prev = tail;
        tail = temp;
    }

    if(updateDisk)
    {
        tail->pos = nextPosition++;
        updateAdditionOnDisk(tail);
    }
}

bool Linklist::insert(int data, int location)
{
    if(isExist(data))
    {
        return false;
    }

    Node *temp  = new (std::nothrow) Node(data);
    if(temp == NULL)
    {
       return false;
    }

    Node *it = head;
    while(it != NULL)
    {
        if(it->pos > location)
        {
            break;
        }
        it = it->next;
    }

    if(it)
    {
        temp->prev = it->prev;
        temp->next = it;
        it->prev->next = temp;
        it->prev = temp;
    }

    //tail->position = updateAdditionOnDisk(data, nextAvailablePos);
}

bool Linklist::erase(int data)
{
    if(tail == NULL)
        return false;

    Node *temp = head;

    while(temp != NULL)
    {
        if(temp->data == data)
        {
            //nextAvailablePos = updateDeletionOnDisk(temp->position, nextAvailablePos);
            if(temp == head)
            {
                if(head->next)
                {
                    head = head->next;
                    head->prev = NULL;
                    delete temp;
                }
                else
                {
                    delete head;
                    head = NULL;
                    tail = NULL;
                }
                return true;
            }
            else if(temp == tail)
            {
                if(head == tail)
                {
                    delete head;
                    head = NULL;
                    tail = NULL;
                }
                else
                {
                    tail = tail->prev;
                    tail->next = NULL;
                    delete temp;
                }
                return true;
            }
            else
            {
                temp->prev->next = temp->next;
                temp->next->prev = temp->prev;
                delete temp;
                return true;
            }
        }
        temp = temp->next;

    }
    return false;
}

bool Linklist::isExist(int data)
{
    Node *temp = head;

    while(temp != NULL)
    {

       if(temp->data == data)
       {
            return true;
       }
       temp = temp->next;

    }
    return false;
}

void Linklist::display( )
{
    Node *temp = head;
    while(temp != NULL)
    {
        std::cout<<temp->data;
        if(temp->next)
        {
            std::cout<<"-->";
        }
        temp = temp->next;
    }
}

int Linklist::updateAdditionOnDisk(Node *node)
{
    oFile.seekp (0, std::ios::beg);
    oFile.write( (char*)&nextPosition, sizeof(int) );
    oFile.flush();

    int count = 0,pos = 0;
    bool inserted = false;
    Node n(-1);
    iFile.seekg (0, std::ios::beg);
    iFile.read((char*)&pos, sizeof(int));
    while(!iFile.eof())
    {
        std::cout<<"iFile is good";
        if(n.pos == -1)
        {
            oFile.seekp(sizeof(int) + (sizeof(Node) * count) , std::ios::beg);
            oFile.write( (char*)node, sizeof(Node) );
            oFile.flush();
            inserted = true;
            break;
        }
        count++;
    }

    if(!inserted)
    {
        oFile.seekp(sizeof(int), std::ios::beg);
        oFile.write( (char*)node, sizeof(Node) );
        oFile.flush();
    }
}

int Linklist::updateDeletionOnDisk(int data)
{
    int temp = nextPosition + 1;
    oFile.seekp (0, std::ios::beg);
    oFile.write( (char*)&nextPosition, sizeof(int) );
    oFile.flush();

    int count = 0,pos = 0;
    bool inserted = false;
    Node n(-1);
    n.pos = -1;
    iFile.seekg (0, std::ios::beg);
    iFile.read((char*)&pos, sizeof(int));
    while(!iFile.eof())
    {
        std::cout<<"iFile is good";
        iFile.read((char*)&n, sizeof(int));
        if(n.data == data)
        {
            n.pos = -1;
            oFile.seekp(sizeof(int) + (sizeof(Node) * count) , std::ios::beg);
            oFile.write( (char*)&n, sizeof(Node) );
            oFile.flush();
            break;
        }
        count++;
    }

}

void Linklist::createListFromFile ()
{
     Node n(-1);

     iFile.seekg(0, std::ios::beg);
     if(!iFile.eof())
     {
         iFile.read((char*)&nextPosition, sizeof(int));
        while(!iFile.eof())
        {
            iFile.read((char*)&n, sizeof(Node));
        }

     }

}

Linklist::~Linklist()
{
    while(head)
    {
       Node * temp = head;
       head = head->next;
       delete temp;
    }
}

int main ()
{
    char choice;
    int data;

    Linklist l;

    while (1)
    {
        std::cout << "\n\nSelect Opration to performed on LinkList"<<std::endl;
        std::cout << "1 Insert "<<std::endl;
        std::cout << "2 Delete "<<std::endl;
        std::cout << "3 IsExist "<<std::endl;
        std::cout << "4 Display "<<std::endl;
     }

}

Linklist::~Linklist()
{
    while(head)
    {
       Node * temp = head;
       head = head->next;
       delete temp;
    }
}

但是代码给了我垃圾输出。

有人可以指出我在代码中可能遇到的错误。

感谢

3 个答案:

答案 0 :(得分:0)

在函数Linklist::updateAdditionOnDisk()中,局部变量n的目的是什么?您初始化它然后检查它但从不更改其值。也许你应该消除它,只看node? (顺便说一句,应该将其声明为指向const Node的指针,以便在保存时不能错误地修改Node实例。)

我看Linklist::updateAdditionOnDisk()越多,我就越困惑。 pos是一个局部变量,每次调用函数时都会从输出文件中读取它;它从未被使用或修改过。你有一个永远循环的循环,直到n.pos的值不是-1;它还会检查iFile.eof(),但循环不会从iFile读取,因此检查将始终成功或始终失败。 count是一个局部变量,总是从0开始......实际上可能是你的问题。考虑这一行:

oFile.seekp(sizeof(int) + (sizeof(Node) * count) , std::ios::beg);

这使用count在输出文件中进行搜索。但是count将始终为0,因此这将继续寻找文件的开头并覆盖先前的记录。也许你想要pos而不是count?或者也许是node.pos

您是否尝试在调试器中单步执行程序并观察它的作用?就此而言,让它在每个传递中打印变量值count,并观察它在输出文件中的搜索方式。

而且,如果您只是想解决存储值的问题,您可能希望只存储整数值(以计数为前缀)或使用已经编写的已调试库来存储数据你(以JSON格式,或HDF5格式,甚至是SQLite数据库文件)。

Linklist::insert()可能会失败。如果location对于列表中的任何Node实例而言过大,则while循环将运行到最后,it设置为NULL然后没有插入任何内容。此外,您没有任何地方return true表示成功添加。

Linklist::createListFromFile()从不致电insert()。所以它实际上并没有建立一个链表。我认为,您之前发布的代码正在调用insert(),但此代码并未调用它。

抱歉,我没有时间了。以下是一些指南类型的建议:

  • 将链接列表写入磁盘的功能根本不需要查找。只需写下数据记录的数量,然后记下所有记录。

  • 从磁盘读取链表的功能根本不需要查找。只需读取数据记录的数量,然后循环,直到您从磁盘读取了许多记录,从磁盘读取的每个值上调用insert()

  • 您经常致电flush(),但根本不需要这样做。只需编写所有记录,然后关闭输出文件。

  • 写入磁盘的函数应该使用const指针。将数据写入磁盘不应更改数据,因此请使用const声明您的意图。

  • 编写可能有效的最简单代码,然后对其进行测试并确保其按照您希望的方式工作。然后,为其添加更多功能。我建议你编写一个测试程序,制作一个包含值1,2,3,4,5和单步的链表,观察它将该列表保存到磁盘然后读取它并从磁盘文件构建一个新的链表

祝你好运,玩得开心。

答案 1 :(得分:0)

实际上,您的代码实例化Linkedlist的实例,但只是(隐含地)调用其构造函数和析构函数。

你的代码不会调用任何其他内容。

您尚未提供课程Linkedlist的完整声明。所以我们可能只是猜测。在猜测你的代码时,我们可能会猜到很多东西。但可能没有什么可以帮助你。

答案 2 :(得分:0)

您的代码存在很多问题,因此我甚至没有尝试猜测它应该做什么。但是通过浏览它,我发现了两条线:

oFile.write( (char*)node, sizeof(Node) );

iFile.read((char*)&n, sizeof(Node));

您正在编写/读取Node类型的对象,但Node包含指针!!在文件中存储和检索指针没有任何意义!