Error occurs after calling TTree::SetDirectory()

The member function TTree::SetDirectory() causes something wrong with TTree::Draw().

    TFile* f1=new TFile("newfile.root","recreate");
	TFile* f2=new TFile("data_homework_sparse.root");
	TTree* t=f2->Get("T");
	TCanvas* c1=new TCanvas("c1","c1");
	t->Draw("x");   //It works well here;
	TCanvas* c2=new TCanvas("c2","c2");
	t->Draw("x");   //Error occurs here;

The file "“data_homeword_sparse.root” has been uploaded in the attachment.
data_homework_sparse.root (206 KB)


What is your intend with calling “t->SetDirectory(f1);” here? Effectively you are telling the TTree that rather than reading its data from the input file it comes from (f2), it should read the data from the new/empty file (f1) … and this can not possibly work …


Thank you for your reminding! In fact I want to save the TTree from the original file f2 to the new file f1.
First I read the TTree from the file f2 and then change the current directory to f1, then invoke TTree::Write(), then close the file f1. But when I open the file f1 again, and read the TTree from it, then invoke TTree::Draw(), it still doesn’t work, so what should I do if I want to save a TTree from one file to another?

TFile* f2=new TFile(“data_homework_sparse.root”);
TTree* t=f2->Get(“T”);
TFile* f1=new TFile(“newfile.root”,“recreate”);
TTree *t2 = t->CloneTree(-1,“fast”);


Thank you very much!
I got it!