Update TH1 object in root file

Hello,

I have a little problem when trying to update a histogram that is saved to a .root file, and I was wondering whether someone patient here could lend me a hand. :slight_smile:

In short, my question is: is there any method that I can use to update TH1 objects included in a .root file?

I’ll give a bit of background now.
My code is c++ code that also makes use of ROOT libraries, upon compilation with a custom-tailored makefile.

At some point in the program I need to create a root file, write in it a new TH1D object, and then fill this one, within a nested double cycle, whenever it needs to be fed some values.
These operations are performed by three methods of a specific class, Analizer:
-a set method that creates the new root file and writes the histogram in it;
-a fill method, that opens the existing root file, cycles through all the particle in a single event (an outer cycle that iterates on all the events is in the main program), fills the histo with particles energies, then closes the file;
-a draw method that prints the histo on a canvas.

Here follows most of the code in Analizer’s fill method:

[code]Event* ev_generated = data->getEvent(“generated”);

         TFile *f_generated = new TFile (generated, "UPDATE");				
         TH1D *hE_gen = (TH1D*)f_generated->Get("hE_gen");					

         for(Event::const_iterator j = ev_generated->begin(); j != ev_generated->end(); j++)
     	   {
	    
			 Particle* p = *j;
			 E=p->getE();
			 hE_gen->Fill(E);
			    
			 cout << "Number of entries in the histo " << hE_gen->GetEntries() << endl;
			     
			     }
		
			hE_gen->Write();
	
            
			f_generated->Close();[/code]

Notice the hE_gen->Write() line.
When I don’t include it, the histo loses memory of the values I filled it with in the previous times when the method was called, from the outer cycle in the main program.
If I do include it, however, multiple, progressively filled copies of the histogram are saved in the root file, instead of overwriting the old one!

Is there any way to update the histogram, thus avoiding this problem of the multiple copies?

Thank you a lot for your help!

see documentation of TObject::Write

hE_gen->Write(hE_gen->GetName(),kOverwrite);
Rene

Thank you a lot Rene, I should look into the documentation more! :slight_smile:

By the way, the compiler complained about options not being Int_t values, so I tried with: hE_gen->Write(0,2,0); and it seems to work.

Thank you again,

MB