Searching an object in all the directories

Hello,
let us assume that I have a root file with tow directories : Dir1 and Dir2
In Dir 1, I have 2 histograms named hist1_1 et hist1_2 and in Dir2 I have only one histogram named hist2_1
Somethin like that
foo.root

Dir1
–> hist1_1
–> hist1_2
Dir2
–> hist2_1

Is there any way to use the Get method to get hist2_1, such as

TFile *f = new TFile("foo.root"); TH1F *h = (TH1F*)f->Get("hist2_1")
I did not find any method which could do that.
Thanks in advance.

Hi,

The easy way:

TKey *key = f->FindKeyAny("hist2_1"); if (key) TObject *o = key->ReadObj();
Or here is an example of recursive search for an object name:

[code]TObject *searchDir(TDirectory *dir, const char *name) {
TDirectory *dirsav = gDirectory;
TIter next(dir->GetListOfKeys());
TKey *key = 0;
TObject obj = 0;
while ((key = (TKey
)next())) {
if (key->IsFolder()) {
dir->cd(key->GetName());
TDirectory *subdir = gDirectory;
obj = searchDir(subdir, name);
if (obj) return obj;
dirsav->cd();
continue;
}
if (!strncmp(key->GetName(), name, strlen(name)))
return key->ReadObj();
}
return 0;
}

TObject *searchKey(const char *filename, const char *name) {
TFile *f = TFile::Open(filename);
if (f->IsZombie()) {
std::cout << “File " << filename << " does not exist!”, << std::endl;
return;
}
std::cout << "Reading file ==> " << filename << std::endl;
TObject *obj = searchDir(f, name);
std::cout << "Result: " << obj->IsA()->GetName() << " " << obj->GetName() << std::endl;
if (obj && obj->InheritsFrom(“TH1”))
((TH1 *)obj)->SetDirectory(0);
delete f;
return obj;
}
[/code]
Note that if you already know where it is, you can just call

TH1 *h = (TH1 *)f->Get("Dir2/hist2_1");
Cheers, Bertrand,

Thank you very much. I did not think to use TKey.