TDirectories not created

Hello, I’m trying to create 3 Tdirectories in root file and saving histograms inside them.
I create the directories

TDirectory *EnergyDir = f_in->mkdir("Energy");
    TDirectory *EnergyADCDir = f_in->mkdir("EnergyADC");
    TDirectory *RateDir = f_in->mkdir("Rate");

and i cd into them to write histos

EnergyDir->cd(); 
	 for (int k = 0; k<Nadc; k++) h_EBGO[k]->Write();
	 EnergyADCDir->cd(); 
	 for (int k = 0; k<Nadc; k++)   h_EBGO_ADC[k]->Write();	
	 RateDir->cd(); 
    for (int k = 0; k < Nadc; k++) h_rate[k]->Write();

but opening the root file, I don’t see the directories.

thanks

You open the file with:

TFile* f_in = new TFile(file_to_load);      // open input file

which means ‘read only’. Try:

TFile* f_in = new TFile(file_to_load, "UPDATE");      // open input file

Hi @pcanal thank you, but unfortunately, it didn’t solve

Sorry, I mis-read you code. You probably actually meant:

    TFile f_out(file_to_save, "recreate");              // creates output file
    TDirectory *EnergyDir = f_out->mkdir("Energy");
    TDirectory *EnergyADCDir = f_out->mkdir("EnergyADC");
    TDirectory *RateDir = f_out->mkdir("Rate");

Oh my god…it was a very stupid mistake…due to distraction, but I didn’t notice it!

That was the problem!
I had only to make a bit change to your solution…I had to define

TFile *f_out = new TFile(file_to_save,"RECREATE");

because if it is not a pointer, I couldn’t use "->"

Last question please. If I’m in a directory, how to come back to the file? is it enough

f_out->cd
??

because if it is not a pointer, I couldn’t use "->"

Indeed. I copy/pasted too fast. You can of course also do:

    TFile f_out(file_to_save, "recreate");              // creates output file
    TDirectory *EnergyDir = f_out.mkdir("Energy");
    TDirectory *EnergyADCDir = f_out.mkdir("EnergyADC");
    TDirectory *RateDir = f_out.mkdir("Rate");

Last question please. If I’m in a directory, how to come back to the file? is it enough

f_out->cd

Yes. This is the most explicit way.

Another alternative is :

{ // Start an explicit C++ scope to control object lifetime; this could also be a function for example
   TDirectory::TContext ctxt;  // Record the current directory.
   subdir->cd();
   ... do some stuff ...
} // The end of the scope means `ctxt` is destructed and it reset the current directory to what it was
// before the start of the scope.

Thank you @pcanal

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