How to read tree branch from a root file

Hello ROOTers,

Beginner question here. I am trying to write a macros to read a branch from a root file.
Here is the structure of the root file(resultant.root) - The file contains a TDirectory(ntuplealign) which consists of a TTree(myTree). The TTree has some branches.

void merge() {

	TFile *f1 = new TFile("resultant.root");
    f1->cd();
f1->ls();
 
f1->cd("ntuplealign");
f1->ls();
TTree *myTree;
f1->GetObject("myTree",myTree);
myTree->Print();

}

I am trying to print the contents of the tree at which point I get an error

Error in : Trying to dereference null pointer or trying to call routine taking non-null arguments.
Execution of your code was aborted.
In file included from input_line_8:1:
/Users/Desktop/merge.C:13:2: warning: null passed to a callee that requires a non-null argument [-Wnonnull]
myTree->Print();
^~~~~~
Any help would be very appreciated!

Thanks
Tanvi

Hi,

you can have a look to TTree::Draw https://root.cern.ch/doc/master/classTTree.html#ac4016b174665a086fe16695aad3356e2 and TDataFrame https://root.cern/doc/master/classROOT_1_1Experimental_1_1TDataFrame.html

Cheers,
D

Hi,

Most likely you meant:

gDirectory->GetObject("myTree",myTree);
if (myTree) myTree->Print();
else std::cerr << "Could not find my tree in : " << gDirectory->GetName() << '\n';

Cheers,
Philippe.

Thankyou for the advice !

I edited my code

void merge() {

	TFile *f1 = new TFile("resultant.root");
    f1->cd();
f1->ls();
 
f1->cd("ntupleEcalAlignment");
f1->ls();
gDirectory->GetObject("myTree",myTree);
    if (myTree) myTree->Print();
    else std::cerr << "Could not find my tree in : " << gDirectory->GetName() << '\n';

}

But get the error
error: use of undeclared identifier 'myTree’
gDirectory->GetObject(“myTree”,myTree);
error: use of undeclared identifier 'myTree’
if (myTree) myTree->Print();
error: use of undeclared identifier 'myTree’
if (myTree) myTree->Print();

well you still need to declare the variable …

TTree *myTree;
gDirectory->GetObject("myTree",myTree);

That was a stupid mistake!
Thanks again

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