Reading histo from file into an array of histos

I have several root files containing a TH1F histo called “h1” in all files (different data, but same name in all files), and want to open each file and store the histos in an array.
The following code does this same thing, successfully, for TGraphs (stored as “gr” in the files):

  TGraph *gr[12];
  TFile *f;
  Char_t temp[40];
  for (Int_t i=0; i<12; i++) {
    sprintf(temp,"%s%s",cities[i],"_monthly.root");
    f = new TFile(temp);
    gr[i] = (TGraph*) f->Get("gr");
    f->Close();
    delete f;
  }

But the same code does not work for TH1F, i.e., the following does not work:

  TH1F *h[12];
  TFile *f;
  Char_t temp[40];
  for (Int_t i=0; i<12; i++) {
    sprintf(temp,"%s%s",cities[i],"_daily.root");
    f = new TFile(temp);
    h[i] = (TH1F*) f->Get("h1");
    f->Close();
    delete f;
  }

Is there a reason why this should work for TGraph and not for TH1F? Or is this a bug in ROOT? I’ve tried versions 5.34/05 and 5.32/01 with the same results.

  • Daniel

Hi Daniel,

Try to add h[i]->SetDirectory(0), as shown here:

for (Int_t i=0; i<12; i++) { sprintf(temp,"%s%s",cities[i],"_daily.root"); f = new TFile(temp); h[i] = (TH1F*) f->Get("h1"); h[i]->SetDirectory(0); f->Close(); delete f; }
And take a look at the “Object Ownership” chapter of the User’s Guide :wink:

Cheers, Bertrand.

Dear Bertrand,
thank you, this worked perfeclty!
Cheers,
Daniel