How to move a TTree from one file to another?

I have difficulty writing an object from one file to another, please who can help me?

void test()
{
	TFile* f1=new TFile("newfile.root","recreate");
	TFile* f2=new TFile("data_homework_sparse.root");
	TTree* t=(TTree*)f2->Get("T");
	TCanvas* c1=new TCanvas("c1","c1");
	t->Draw("x"); //It works well here;
	c1->Update();
	f1->cd();
	t->Write();
	f1.Close();
	f2.Close();
	//Then open the file f1 again and try to draw the tree;
	f1=new TFile("newfile.root");
	t=(TTree*)f1->Get("T");
	t->Print();//It prints the correct information about the tree;
	t->Draw("x");//Error occurs here!

}

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

I have modified your script, see below

Rene

[code]void test()
{
TFile* f1=new TFile(“newfile.root”,“recreate”);
TFile* f2=new TFile(“data_homework_sparse.root”);
TTree* t=(TTree*)f2->Get(“T”);
TCanvas* c1=new TCanvas(“c1”,“c1”);
t->Draw(“x”); //It works well here;
c1->Update();
f1->cd();
TTree t2 = (TTree)t->CloneTree();
t2->Write();
delete f1;
delete f2;
//Then open the file f1 again and try to draw the tree;
f1=new TFile(“newfile.root”);
t=(TTree*)f1->Get(“T”);
t->Print();//It prints the correct information about the tree;
t->Draw(“x”);//Error occurs here!

}
[/code]

I got it!
Thank you!

TFile contains a lot of objects - TTree, TH1, etc.
How to transfer these objects to another file in a general way?

Hi,

You can try to use hadd (see this howto), or you can read objects in memory from the source file and write to the destination file (as described in this topic)

Cheers, Bertrand.

You can also have a look at the command line utilities . And also this page.