Opening multiple root files

Hello,

I want to open two root files, one for data output and one for input, within a geant4 simulation.

I tried various methods to get this working, but my “best” result is with the following code:

G4bool hbarPrimGenAction::open_root_spectrum(G4String filename){
  if(fileisopen) return true;
  //std::cout << "READING FILE" << std::endl;
  TFile *f = new TFile(filename.c_str(),"READ");
  if(!f->IsOpen()) return false;
  TH1D *velspectr2;
  f->GetObject("velocity-z", velspectr2);
  velspectr = TH1D(*velspectr2);
  //if(velspectr == 0) return false;
  f->Close();
  //std::cout << "FILE CLOSED" << std::endl;
  fileisopen = true;
  return true; }

this works for reading the data, and using the spectrum within the root file as input for primary particle generation, but afterwards I cant write the results of the simulation to a root file… I always get error messages like this:

[quote][…]
Error in TROOT::WriteTObject: The current directory (root) is not associated with a file. The object (VelocityDist) has not been written.
Error in TROOT::WriteTObject: The current directory (root) is not associated with a file. The object (VelocityDistDet) has not been written.
[…][/quote]

but if I turn the input spectrum off and use a Maxwell distribution or something similar, I have no problem with getting the output… does anyone have an idea what I’m doing wrong?

Thanks,
Clemens

I’m afraid that after you do “f->Close();”, both histograms “velspectr2” and “velspectr” are gone.
Try this: G4bool hbarPrimGenAction::open_root_spectrum(G4String filename) { if(fileisopen) return true; TFile *f = new TFile(filename.c_str(), "READ"); gROOT->cd(); if(!(f->IsOpen())) {delete f; return false;} TH1D *velspectr2; f->GetObject("velocity-z", velspectr2); if(!velspectr2) {delete f; return false;} // TH1D *velspectr; velspectr = new TH1D(*velspectr2); delete f; fileisopen = true; return true; }

thanks for that quick response, your code works quite well and I can create the particles according to my input spectrum, but when saving the results to another root file I still get the same error as described above.

Do you think, that this might have something to do with the fact that i open the output rootfile before opening the input file?

Simply do:
MyOutputTFile->cd();
before you do:
velspectr->Write();
and, in the end, do not forget to:
delete MyOutputTFile;
(BTW. Note that, I “improved” the source code, in my first post above, quite a few times … so, maybe have a look at the “last / best” version again.)

Thanks a lot, now everything is working!

It seems that your code improvements also closed some memory leaks, so also thanks for that!