在文本文件预订中写二叉树

时间:2011-12-23 17:45:01

标签: c++ recursion binary-tree out

我有一个从二叉树中写东西的函数。当我运行它时,它只是在txt中写入树的根。谁能告诉我这里有什么问题?

void tree::wrte(person *p)
{
    ofstream out("myfile.txt");

    struct register{
        char ID[15];    
        char name[30];      
        char surname[30];       
    };                              

    register reg;   
    if(!(mybook=fopen("myfile.txt","a+")))
    {                           
        if (!(mybook=fopen("myfile.txt","w+")))
        {                                             
            cerr<<"Couldnt opened"<<endl;return;                  
        }                                                                
    }                                          
    if(p)                   
    {                               
        strcpy(reg.name,p->name);               
        strcpy(reg.ID,p->ID);                           
        strcpy(reg.surname,p->surname);                         
        out << reg.ID <<'\t'<<reg.name<<'\t'<<reg.surname<<'\t'<<endl;  
        wrte(p->left);                                                          
        wrte(p->right);                                                                 
    }                                                                                       
    out.close();                
}

1 个答案:

答案 0 :(得分:3)

如果你真的必须在每次调用wrte()时打开文件,我会在递归调用write之前更改代码以关闭当前流:

if(p)
{
    ...
    out << reg.ID <<'\t'<<reg.name<<'\t'<<reg.surname<<'\t'<<endl;
    out.close();
    wrte(p->left);
    wrte(p->right);
    ...

但是,更好的设计是将ostream传递给wrte()函数:

void tree::wrte(ostream& out, person *p){
    ...
    if(p)
    {
        ...
        out << reg.ID <<'\t'<<reg.name<<'\t'<<reg.surname<<'\t'<<endl;
        wrte(out, p->left);
        wrte(out, p->right);
    }
    ...
}

然后在第一次调用wrte()之前打开输出流:

int main()
{
    ...
    ofstream out("myfile.txt");

    ...
    tree_ptr->wrte(out, p);
    out.close();
    ...
}