Close the file after reading histogram

I have gone through this discussion : Get histogram and close file
The code I have is slightly different from what’s given, its just that I initialized the TFile as a pointer i.e. TFile *f, but when I do a SetDirectory(0), the code crashes.

TFile *file = new TFile(“somefile.root”);
TH1D h = (TH1D) file->Get(“h1”);
h->SetDirectory(0)l; // Code crashes
file->Close()

First, it shoud be TH1D *h (instead of TH1D h), then, here is how you should do it:

TFile *file = TFile::Open("somefile.root");
if (!file) {
   cout << "Cannot open somefile.root!" << endl;
   return;
}
TH1D *h;
file->GetObject("h1", h);
if (!h) {
   cout << "Cannot find object h1 of type TH1D in somefile.root!" << endl;
   return;
}
h->SetDirectory(0);
file->Close();

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