Write histograms to a root file

Hi root users,
I want to save some histograms into a root file, the code is like:

TFile f(“read.root”);

TH1F* h_all[60];

TFile f1(“write.root”,“RECREATE”);
for(int m=1;m<=50;m++){

sprintf(hPointer,“h_all_eta%s”,&eta[m]);
h_all[m]= new TH1F(hPointer,“blah”,1200,0,10.986);

for(i=0;i<20;i++){
sprintf(name[i],“hist_%s_%s”, &eta[m],&phi[i]);
TH1F* h = (TH1F*)gDirectory->Get(name[i]);
h_all[m]->Add(h);
}
}

f1->Write();
f1->Close();
}

but in write.root, there is only the first histogram h_all_eta01. How can I save all the 50 histograms in the file?

Thanks for your help,

Lei

I am not sure to understand what you try to do.
If you want to read in all your histograms from the
file “read.root”, add them to h_all[m], then save
them to 'write.root", you should modify your test as follows:

TFile f(“read.root”);

TH1F* h_all[60];

TFile *f1 = new TFile(“write.root”,“RECREATE”);
for(int m=1;m<=50;m++){

 sprintf(hPointer,"h_all_eta%s",&eta[m]); 
 h_all[m]= new TH1F(hPointer,"blah",1200,0,10.986); 

 for(i=0;i<20;i++){ 
   sprintf(name[i],"hist_%s_%s", &eta[m],&phi[i]); 
   TH1F* h = (TH1F*)f.Get(name[i]); 
   h->SetDirectory(f1);
   h_all[m]->Add(h); 
 } 

}

f1->Write();
f1->Close();

Rene

Hi Rene,
Thanks a lot! Your code does work except I want to save all "h_all[m]"s so that I modified a little bit as below.
for(i=0;i<20;i++){
sprintf(name[i],“hist_%s_%s”, &eta[m],&phi[i]);
TH1F* h = (TH1F*)f.Get(name[i]);
//h->SetDirectory(f1);
h_all[m]->Add(h);
}
h_all[m]->SetDirectory(f1);
}
f1->Write();
f1->Close();

Thanks,
Lei