Create and fill many TFiles with same TTree

Hi,

I am trying to create many TFiles having similar TTree. For that I wrote macro (given below).

In the macro, I am creating 8 TFiles with option “RECREATE” and pushing back to a vector. Then in the event loop I am again defining TFile with same name but with option “UPDATE” so that it will add the data in the created TFile for each event. Currently, while UPDATE I am just redifining the name of TFile. However, I would like to just grab name of TFile from the first definition of TFile (I mean from the vector where I saved all TFiles). But, I am unable to do this. Please let me know how I can do this.

void many_TFile_having_sameTTree() {
    // Create trees and store in list
    TTree   *tree = 0;
    std::vector<TFile*> tfile_list;
    Int_t Track;
    TString name[8] = { "a", "b", "c", "d", "e", "f", "g", "h" };
    for (Int_t i=0; i<8; i++) {
        TFile *hfile = new TFile(name[i]+"_AFile.root","RECREATE","Example");
        tfile_list.push_back(hfile);
        //delete hfile;
    }

    // Fill trees with data
    //for (auto obj : tfile_list){
    for (auto obj : name) { // Loop over trees
        cout << "==> " << obj << endl;
        //TString filename = obj->GetName();
        TString filename = obj+"_AFile.root";
        TFile *hfile = new TFile(filename,"UPDATE","Example");
        tree = new TTree("otree", "");
        Track = -1;
        tree->Branch( "Track", &Track, "Track/I");
        cout << "DEBUG..." << endl;
        for (Int_t id=0; id<8; id++) { // Loop over event numbers
            Track = id*2;
            tree->Fill();
        }
        tree->Write();
        delete tree;
        tree = 0;
        delete hfile;
    }
}

This is an example macro. Finally, I need to add this in TSelector so that I can use PROOF.


ROOT Version: ROOT 6.12/06
Platform: Not Provided
Compiler: Not Provided


Hi @ramkrishna,
if I understand correctly you are reopening the same TFile in UPDATE while you have the first TFile, corresponding to the same file on disk, still open.

I think it might be better (simpler, safer) to just use the TFile you already have! For example:

// Fill trees with data
for (int i = 0; i < 8; ++i) {
  file = tfile_list[i];
  file->cd(); // make this file the current file
  tree = new TTree("otree", "");
  // etc...

Actually you might do everything with a single for loop that creates a file, creates the TTree for that file, fills it, and then deletes the tree and the file.

Hope this helps!
Enrico

Thanks @eguiraud. Actually, I need to implement this in PROOF. Where, I need to define all the TFiles in SlaceBegin. Then inside Process I need to fill each TFiles. So, I am not doing this in one loop.

Please correct, if I am wrong.

with regards,
Ram

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