I encode a text file using a huffman tree. Which print out to the screen and and output to a file. File only contains the last line that prints to the console.

void traverse(string code = "") const {
		string outputFile = "huffman.txt";
		ofstream outfile(outputFile.c_str());

		if (child0 !=NULL) {

			static_cast<huffman_item<dtype> >( *child0).traverse(code + '0' );		

			static_cast<huffman_item<dtype> >( *child1).traverse(code + '1' );

		} else{

			outfile << data << freq << code << endl;
			cout << " Data: " << data << " Frequency: " << freq << " Code: " << code << endl;



This is method. Can someone please help me!

8 Years
Discussion Span
Last Post by skatamatic

Is recursion really necessary for this? Whenever possible avoid using it. It's inefficient, hard to implement, and hard to debug. It seems as though the function recursively calls itself until it is at the end of the list, then it displays a line. In each recursive call, you should be outputting a line, otherwise it will traverse to the end and display the last line. If recursion isn't necessary, use a loop instead.


figure out the problem! this is a recursive function...

Ummm...ok? I'm pretty sure I told you the solution. Being polite will get you farther in life.


yeah it creates a output file each time the function is called. the way i have it setup i need a recursive function.


I replied the before I read you solution. Didn't expect a quick response. Sorry mate!

I still have the same problem though! Need to figure out a way to edit an existing file rather than create a new file. Or maybe I should create a file before the function is called...


Open the file in append mode.

ostream fOut;
fOut.open("file.dat", ios::append);

I'm pretty sure that's how it's done.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.