为fstream添加NULL终止符

时间:2012-12-11 23:40:37

标签: c++

我正在尝试编写一个程序来保存链表的内容(每个单独的列表称为一个位置并包含多种数据类型)。代码编译但意外终止;它将我引用​​到ifstream库中的行(即使我只想使用写作)

*_Str = _Elem();    // add terminating null character

有没有人知道出了什么问题?

   //saves a single locality onto a file
    void fSave_locality(Clinked *current, fstream *fout)
    {
        fout->write(current->site_name,100);
        fout->write((char*) &current->cood_x,sizeof(double));
        fout->write((char*) &current->cood_y,sizeof(double)); 
        fout->write((char *) &current->dip,sizeof(double)); 
        fout->write((char *) &current->strike,sizeof(double)); 

        if (current->next!=NULL) fSave_locality(current->next,fout);
    }

    void fSave_list(char* fname)
    {
        fstream *fout;
        do
        {
            cout<<"Would you like to save as a (b)inary or (t)ext file? ";
            test = getch();
            cout<<"Enter file name (make sure its unique!): ";
            cin.getline(fname,100);

            if(toupper(test)=='T') fout->open(fname, fstream::out);
            if(toupper(test)=='B') fout->open(fname, fstream::out| fstream::binary);
        }
        while(toupper(test)!='T' || toupper(test)!='B');

        if(fout->fail())
        {
            cout<<"unable to open file.\n";
            exit(0);
        } //it gets to here without any problems. 

        current = start;
        while(current->next!=NULL)
            {
                fSave_locality(current, fout);
                current=current->next; //repeat for the next object in the list
            }
        fout->close();
    }

1 个答案:

答案 0 :(得分:0)

我不明白你为什么要在同一时间递归递归迭代? 只需选择其中一个,我更改了代码,您还需要为while循环设置正确的限制,并确保不使用null对象并尝试访问null对象上的元素。

  void fSave_locality(Clinked *current, fstream *fout)
    {
        fout->write(current->site_name,100);
        fout->write((char*) &current->cood_x,sizeof(double));
        fout->write((char*) &current->cood_y,sizeof(double)); 
        fout->write((char *) &current->dip,sizeof(double)); 
        fout->write((char *) &current->strike,sizeof(double)); 

        //if (current->next!=NULL) fSave_locality(current->next,fout); // comment this out
    }

并更改以下部分:

while(current!=NULL)
    {
        fSave_locality(current, fout);  // you should either comment this one or the recursive one
        current=current->next; //repeat for the next object in the list
    }