Root trees in several files

Hey, i have a small problem:
I have several trees, and each tree has to go into one File.
Now i created all the trees and files pairwise (first TFile, then TTree)
If i write the trees now in a loop everything is put into the last file opened.
Why is that? I even called SetDirectory(file) for each tree after i created the file i want it to go into… I am puzzled.

Some code fragments:

Creation of trees etc in a loop over i

pot[i].file = new TFile(names[i].c_str(),"RECREATE"); pot[i].tree=new TTree("data","TEST"); pot[i].tree->Branch("pm",&pot[i].hitmap,"pm[10][10]/O"); pot[i].tree->SetDirectory(pot[i].file);

and storage in a loop over i

pot[i].tree->Write(); pot[i].file->Close();

Thanks for any help


Dopot[i].file->Write(); pot[i].file->Close();


PS. TTree::Write will explicitly write the tree header in the current directory.

Thanks alot, that did the Trick :slight_smile:


I always thought that this piece of code was quite dangerous (in my opinion even wrong), because it will cause a segmentation fault, if the trees becomes larger than “MaxTreeSize” (see TTree::SetMaxTreeSize) and root starts to create new output files.

Because of this I assumed, that the only valid code is


Moreover I think that accessing a TFile after calling TTree::Fill() always is an error, because you never know whether TTree::Fill() closed and deleted the TFile which stores the TTree.

Am I wrong? Was the behaviour of ROOT/TTree changed with respect to this feature in the last few versions?

Cheers, J.

Hi Joe,

You are correct. The code I gave only works is the tree never reaches the maximum size.