How to write two different trees into one file?

Suppose I have file file1 from which I get tree tree1.

TFile *f1 = new TFile("file1.root");
TTree *t1 = (TTree*)f1->Get("tree1");

I use this tree to create another tree tree2. Now question is how to write either tree2 to the file1 or write this trees in one file . If I try the first option

f1->cd();
tree2->Write();

the error is something like:

file1.root is not writeable. 

If I try the second option

TFile *f2 = new TFile("file2.root", "RECREATE");
...
f2->cd();
tree1->Write();
tree2->Write();

the following error occurs when I try to read tree1 entries:

...
Error in <TFile::ReadBuffer> error reading all requested bytes from file `file1`, got 0 of 1112
Error in <TFile::ReadBuffer> error reading all requested bytes from file `file1`, got 0 of 1113
...

See the examples in tutorials/tree/copytree*.C

First open the new file f2, then create your second tree tree2. To copy your tree t1 into the new file, use t1->CloneTree, see https://root.cern.ch/doc/master/classTTree.html#a76927d17a94d091d4ef1ed0ba7ef3383.

Think of large trees which don’t fit in your memory. ROOT still works because it already writes to disk when filling the tree. That is why the output file needs to be open already in the beginning.

Your first option desn’t work because you have opened f1 for reading only. You could pass the option “UPDATE” when opening f1. When you are sure you are doing “the right thing”, you can do that. Otherwise I suggest to use your second option and use a new file. That way you don’t change your input file and you can rerun your program and still get the same result.

Also see How to Quickly Inspect the Content of a File?

Very convenient option. Thank you.

For that just open the file for update:

TFile *f1 = new TFile("file1.root","UPDATE");

Cheers,
Philippe.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.