Question

I am trying to write the information in a binary tree to a txt file. All it is doing is deleting the records that were in the txt file and not writing anything.

This is what I have so far but I honestly have no idea. The binary tree contains objects of the class customer in case it's important. Also p is the root of the tree.

template <class elemType>
void bSearchTreeType<elemType>::writeFileTree(binaryTreeNode<elemType> *p) const
{
    //Root=NULL;                       
    ofstream fin;
    fin.open("Customers.txt");

    if (p != NULL)
    {
        writeFileTree(p->llink);
        //cout << p->info << " ";
        fin << p->info;
        writeFileTree(p->rlink);
    }

    fin.close();
}

Here's my overloaded operator.

ostream& operator >> (ostream& os, const Customer &cust)
{
    //print();
    os << cust.getCustNum() << endl << cust.getName() << endl;
    Address address = cust.getAddress();
    os << address.getStreet() << endl << address.getCity() << endl << address.getState() << endl << address.getZip() << endl;
    //address.print();
    return os;
}
Was it helpful?

Solution

Each recursed call opens (and likely fails in doing so) the same file on-disk with a new file object. That isn't going to work. You need to open the file outside of all of this and pass it as a reference parameter

template <class elemType>
void bSearchTreeType<elemType>::writeFileTree(std::ostream& os, binaryTreeNode<elemType> *p) const
{
    if (p != NULL)
    {
        writeFileTree(os, p->llink);
        os << p->info << '\n';
        writeFileTree(os, p->rlink);
    }
}

Make the caller open and close the file. And your node pointers should (likely) be const parameters, btw.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top