Find Histogram within TDirectory

I have created a list of histograms and saved them to a list within a TDirectory, the structure is as follows:

TFile**		OutputFileRoot.root	
 TFile*		OutputFileRoot.root	
  TDirectoryFile*		MyList	MyList
   KEY: TH1D	Hist1;1	Hist1
   KEY: TH1D	Hist2;1	Hist2

I’m trying to create a macro to open each histogram and fit it, but when I plot the histograms they’re blank.
My code is currently:

TFile * file = new TFile(OutputFileRoot.root);
TList * list = (TList *) file->GetDirectory(MyList)->GetListOfKeys();
TH1D* histo = (TH1D*)list->FindObject("Hist1");

All that appears is a blank canvas. I’ve checked that the histogram exists by doing ‘if(!histo) std::cout<<“no histo”<<std::endl;’, and nothing is printed, but if I change the name to something that I know doesn’t exist then the statement is printed. So an object with this name exists and is cast to a TH1D*.

Where am I going wrong? Thanks in advance for any help.

The content of GetListOfKeys() are TKey(s).

TH1D* histo = dynamic_cast<TH1D*>(list->FindObject("Hist1"));
‘if(!histo) std::cout<<“no histo”<<std::endl;’, 

will print the message. Instead:

TKey *key = dynamic_cast<TKey*>(list->FindObject("Hist1"));
if (!key) { cout << "No key for Hist1\n"; return; }
TH1D* histo = key->ReadObject<TH1D*>("Hist1");
‘if(!histo) std::cout<<“no histo in key”<<std::endl;’, 

This gives me the error: “Error: Symbol key is not defined in current scope”. Changing the object searched for in the TKey declaration to

TKey *key = dynamic_cast<TKey*>(list->FindObject("Hist1;1"));

Finds the key, but

TH1D* histo = key->ReadObject<TH1D*>("Hist1");

then gives me the error:

Error: illegal pointer to class object key 0x0 303

I was too minimal in my suggestions. [It is not important but puzzling that the previous code was returning a value (then mis-used) but the new code did not]. What you really should be using in order to be able to find the newest key for a name is:

TKey *key = file->GetDirectory("MyList")->GetKey("Hist1");

and in

TH1D* histo = key->ReadObject<TH1D*>("Hist1");

I made a typo, I meant:

TH1D* histo = key->ReadObject<TH1D*>();

We resolved the problem differently, it seems you can call Get() directly on the file:

 TFile * File = new TFile("OutputFileRoot.root");
    std::cout<<"No File."<<std::endl;

 TH1D *h;

 for(Int_t ii=0;ii<91;ii++){
    name = Form("Hist%d",ii);
    h = (TH1D*)File->Get(name.c_str());

Works a charm!

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