TChain empty

Hello, when I chain a number of root files together it works fine for that session (the chained branches are present), but when I write I get an empty tree in the output.

#include “TFile.h”
#include “TTree.h”
#include “TBrowser.h”
#include “TH1.h”
#include “TH2.h”
#include “TRandom.h”
#include “TChain.h”

TChain * ch;

void chain_files()
{
gStyle->SetPalette(1);

TFile foutput("/mypath/MyOutput.root",“RECREATE”);

ch = new TChain(“Analysed_Data”);

for(Int_t i=557;i<640;i++)
{
if((i>561&&i<565)||(i==566)||(i>567&&i<573)||(i>581&&i<605)||(i>608&&i<628)||(i>613&&i<616)||(i>620&&i<627))continue;

  sprintf(file1,"/mypath/Run%i_cal.root",i);  

   //Adding files
   
   ch->Add(file1);
   
 }
 
 ch->StartViewer();
 
 c2 = new TCanvas("c2","My Canvas",200,10,700,500);

  ch->Write();

 foutput.Write();  

}

Thanks in advance, Ben.

Hi Ben,

The TChain object was not written to the file you expected. Instead of ch->Write();Usefoutput.cd(); ch->Write();or better yet:foutput->WriteObject(ch,ch->GetName())

Cheers,
Philippe.

PS. This is due to the fact that for convenience reason, opening a file change the current ROOT directory to the file you just opened and ch->Write() request writting in the current directory.