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
...
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.