-
output tree to file?
i'm trying to output a tree to a file. here's what i was trying:
Code:
save(treenode *treeroot, ofstream outfile){
if(!treeroot) return;
save(treeroot->left,outfile);
oufile<<treeroot->data;
save(treeroot->right,outfile);
}
int main(){
treenode *treeroot;
//do stuff
ofstream outfile("file.txt",ios::out);
save(treeroot, outfile);
}
the error i got was ios is private, or something like that.
how can i get this to work, or is there a better way to do this?
another thing i was wondering, is there a way to output to a file without deleteing the data already in the file?
for example: if i had a file file.txt with the data from the tree in it, and then i ran the program and added stuff to the tree, can i open file.txt and add only the new element of the tree, or do i have to outfile the whole tree again?
thanks.
-
ofstream
ios::app will open the file for append... a nifty trick is to open the file for append and if it fails the first time open it for out so that it will get created. The other mention is that you are recreating an ofstream object each time that you call the save function. I would try a pointer instead it should work.
I would redeclare the function like this:
save(treenode *treeroot, ofstream* outfile){
if(!treeroot) return;
save(treeroot->left,outfile);
*oufile<<treeroot->data;
save(treeroot->right,outfile);
}
Also the tree root type must be global and have all members public for outfile to be able to access it. The first call to the save function will look like this
save( treeroot, &outfile)
Sometime after the file must be closed.