Load histograms in root files

Hello,

I would like to load histograms in the root file named ‘AnalysisResults.root’.
I’ve usually used these below commands for loading histograms.

But, now I cannot load histograms.
I think it is because that there is sub-directory in the ‘AnalysisResults.root’ file.
For your information, I attached one screenshot.

In case that there is sub-directory in the root file, How can I load histograms in the file?

Many thanks,
Jiyoung

TFile *file = new TFile("AnalysisResults.root") 
TDirectory *current_sourcedir = gDirectory;
TIter nextkey( current_sourcedir->GetListOfKeys() );
TKey *key;

 while((key = (TKey*)nextkey())){      
TObject *obj = key->ReadObj();
string histName = obj->GetName();

   if( histName == "fHistRejectionReason_0"  ){
   TH1 *histoObj = (TH1*)obj;
   HistList->Add(histoObj);
   }
}


Hi,

this macro will get you started. You basically would need to explore the “directory structure” of the TFile. The simplest approach consist in using a recusrsive function.

using objList =  std::list<TH1*>;

void exploreDir(TDirectory* d, objList& HistList)
{
  auto keys = d->GetListOfKeys();
  for(auto keyAsObj : *keys){
    auto key = (TKey*) keyAsObj;
    auto obj = key->ReadObj();
    string histName = obj->GetName();
//    cout << histName << endl;
    if (auto h = dynamic_cast<TH1*>(obj)) HistList.push_back(h);
    if (auto subd = dynamic_cast<TDirectory*>(obj)) exploreDir(subd, HistList);
  }
}

void explore() {
  auto file = new TFile("f2.root");
  auto current_sourcedir = gDirectory;
  objList HistList;
  exploreDir(file,HistList);
  std::cout << "The histograms found are:" << std::endl;
  for(auto h : HistList) {
     std::cout << h->GetName() << std::endl;
  }
}

Cheers,
Danilo