Problem merging trees

Dear all,

I would like to merge TTrees from different files. The code snippet below works fine. In my actual script, however, I am looping over several hundred files. Therefore I would like to include a f->Close() statement. This, however, kills the TTree in the file and I get a SegFault when trying to merge the TTrees. In order to avoid this I added the tree->SetDirectory(0) statement. The script runs without any errors but the output TTree has very weird entries (they are basically all the same). What can I do to fix this?

Thank you very much in advance!

P.S.: I cannot attach the root files because they are too large, if someone is interested I can maybe find a solution in order to provide them.

#include <TFile.h>
#include <TTree.h>
#include <TCanvas.h>
#include <iostream>
#include <fstream>

void merge_trees()  {

  TFile *f;
  TList * trees = new TList();
  TTree *tree = new TTree();

  f = new TFile("events_0.root");
  tree = (TTree*)f->Get("ParTree_PMBgMaker_Off");
  // f->Close();

  f = new TFile("events_1.root");
  tree = (TTree*)f->Get("ParTree_PMBgMaker_Off");

  cout << "After loop" << endl;
  cout << "Found " << trees->GetSize() << " trees" << endl;

  TFile *out = new TFile("out.root","RECREATE");

  TTree *newtree = tree->CloneTree(0);



Did you try to use TTree::MergeTrees? For example, in your code:

TTree *newtree = TTree::MergeTrees(trees);
Cheers, Bertrand.


But you can not. Each of the TTree still need to access its data from inside the file (unless you explicitly load all of it in memory … but you are extremely unlikely to have enough memory).

[quote] In order to avoid this I added the tree->SetDirectory(0) statement. [/quote]This explicitly detach the TTree from its file and thus its data …

In order to do the merge you will have to process only a few files at the time.

Note that all of this (and more) is handled by TFileMerger are the command line executable ‘hadd’.



thank you very much for your answers.

Yes, that did not even give the correct number of entries in the merged tree

Alright, thank you - I am not 100% aware how the data in TTrees is handled internally.