TFile *file = new TFile("input.root", "READ"); TObject *obj = file->FindObjectAny("tree1"); if (obj) { TTree *tree = dynamic_cast(obj); // Do something with the tree } file->Close();
TFile *file = new TFile("data.root", "READ"); TKey *key; TIter next(file->GetListOfKeys()); while ((key = (TKey*)next())) { TObject *obj = file->FindObjectAny(key->GetName()); if (obj && obj->IsA()->InheritsFrom("TH1")) { TH1 *hist = dynamic_castIn this example, we first create a new TFile object to read the data file. Then we use a TIter object to iterate over all the keys in the file. For each key, we use the FindObjectAny method to search for the object with the same name as the key. If the object is found and it inherits from the TH1 class, we cast it to a TH1 object using dynamic_cast and perform some operation on it. Finally, we close the file.(obj); // Do something with the histogram } } file->Close();