Saving histograms to different files

From this code I would expect hist_A to be saved in file_A and hist_B to be saved in file_B as instructed by TH1::SetDirectory:

  TFile * file_A = TFile::Open("fileA.root", "RECREATE");
  TFile * file_B = TFile::Open("fileB.root", "RECREATE");
  TH1F h_A("h_A", "h_A", 20, -5, 5);
  h_A.SetDirectory(file_A);
  TH1F h_B("h_B", "h_B", 20, -5, 5);
  h_B.SetDirectory(file_B);
  h_A.FillRandom("gaus");
  h_B.FillRandom("gaus");
  h_A . Write();
  file_A -> Close();
  h_B . Write();
  file_B -> Close();

In reality hist_A and hist_B get saved in file_B, while file_A contains nothing. How to approch this problem?

If I do the following it is working as you expect:

{
   TFile * file_A = TFile::Open("fileA.root", "RECREATE");
   TFile * file_B = TFile::Open("fileB.root", "RECREATE");
   TH1F h_A("h_A", "h_A", 20, -5, 5);
   TH1F h_B("h_B", "h_B", 20, -5, 5);
   h_B.SetDirectory(file_B);
   h_A.FillRandom("gaus");
   h_B.FillRandom("gaus");
   file_A->cd();
   h_A . Write();
   file_B->cd();
   h_B . Write();
   file_A -> Close();
   file_B -> Close();
}

Yes. It also works when I do the following:

   file_A->cd();
   h_A . Write();
   file_A -> Close();//!!!!!!!
   file_B->cd();
   h_B . Write();
   file_B -> Close();

Yes … I do not know why I moved the Close call …

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