Closing all the files in a TChain

Dear experts,

I have a pointer to a TChain (shown in the snippet below). At the end of my macro, I would like to close all the files that were opened when added to the TChain to avoid seeing multiple copies of it in a TBrowser when executing the macro multiple times consecutively (for example after recompiling and rerunning).

TChain *myChain_1 = new TChain("treeName");
myChain->Add("fileName_1");
myChain->Add("fileName_2");
...
myChain->Add("fileName_N");

I’ve attempted to do this by declaring the following function, and calling it at the end of my macro passing the pointer to myChain as the argument: EmptyTChain(myChain_1);

void EmptyTChain(TChain* input_tchain){
    TObjArray *fileElements = inputTChain->GetListOfFiles();
    TIter next(fileElements);
    TChainElement *chainElement=0;
    while (( chainElement=(TChainElement*)next() )) {
        TFile *f = (TFile*)(chainElement->GetTitle());
        f->Close();
    }   
}

Unfortunately this doesn’t get the job done. Any ideas on what I may be doing incorrectly or about better ways of accomplishing this?

Many thanks,

– Nil

I do not understand your problem. TChain::Add does not open the file, unless you specify the nentries parameter different of kBigNumber.
And when you process a TChain, only one file should be open at the time.

Rene

Ah ok, that clarifies something. However…

Suppose I create, for example, 2 pointers to a TChain and add the same file to each, all inside a macro.

TChain* chain_1 = new TChain("tree_1");
TChain* chain_2 = new TChain("tree_2");

chain_1->Add("file.root");
chain_2->Add("file.root");

chain_1->GetEntry();
chain_2->GetEntry();

At this point, I compile and execute. TBrowser shows 2 instances of “file.root” under “ROOT files”. Without quitting root, I compile and execute again. Now TBrowser shows 4 instances of “file.root”. More instances will continue to appear with subsequent executions. Deleting the TChain pointers will cause a segfault. I’m not certain how to go about it.

Thanks,

– Nil

I cannot reproduce this problem.
Could you provide a very small script and 2 small data files reproducing your problem?

Rene