Incorrect output file: c++ (i/o) question

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • drjay1627
    New Member
    • Nov 2008
    • 19

    Incorrect output file: c++ (i/o) question

    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.

    Code:
    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!
  • vmpstr
    New Member
    • Nov 2008
    • 63

    #2
    I can explain the problem to you, but the fix is up to you (because my C++ file i/o abilities aren't particularly strong).

    The problem you have is that in a recursive function, you keep opening the same file for writing. The first time you write, and return, the file stores the first line of output.

    The second time you write, the file is opened again (thus overwriting the old file) and a second line is written.

    So on, and so forth, until the last line. The last line overwrites the second last line, and the program terminates. That is why you have only the last line in the file.

    The solution is to either open the file once outside of the function call, or to reopen it with an append mode (this is where I can't help with code, because I'm not quite sure how to do this) before writing and to make sure to close it after writing.

    There might be some other effect you have with opening files that you do not close until the function exists, but it's "probably ok" (meaning, you shouldn't have it). That is, the first call to the function does not write anything, but it keeps an open handle until every other call of the function has written, and only closes the file afterwards... This might cause some weird behaviour, but then again it might not.

    Comment

    Working...