Trouble with TKey->ReadObj

I’m trying to browse through all the keys/objects in a root file (several
open files actually), with the following strategy:

TDirectory *dir = current_directory;

TIter nextkey(dir->GetListOfKeys());
while (TKey key = (TKey)nextkey()) {
TObject *obj = key->ReadObj();
print out stuff about “obj”
}

and do this recursively over all TDirectories in the file.

If I set “dir” to “file1:/” (the name of the first file), and gDirectory
happens to be “root:/”, then obj == 0, which doesn’t do any good.

So, I figured, just set gDirectory = dir. No good - obj still == 0.

However if I do “gDirectory->cd(dir->GetPath())”, then it all works
fine, with obj != 0, and the object being read in.

In each case, if I print out gDirectory->GetPath(), they’re the same.

So a few questions. First, is there a better way of doing this, ie looping
over all objects in a file. Second, why is gDirectory=dir not the same
as gDirectory->cd(dir->GetPath())? The latter seems very clunky,
and there’s got to be a better way of doing it.

                       cheers,          Charles.

Hi,

Avoid manipulating gDirectory directly. Instead simply use
dir->cd();

Also in the code currently in CVS, the cd should be completely optional.

If your code still does not work with the ROOT cvs repository as of today,
please send us a complete example.

Cheers,
Philippe.

Hi Philippe -

That seems to work, sort of.

It seems as if I need to TFile->Write() on the file before the objects or
even keys appear.

If I create a TFile, with several TDirectories and TH1Fs in it, and
then get hold of one TDirectory *td, then do something like

TIter nextkey(td->GetListOfKeys());
while (TKey key = (TKey)nextkey()) {
cout << key->GetName() << " (" << key->GetClassName() << “)” << endl;
}

all I see are the TDirectories within that one. I don’t see any of the TH1Fs.
If I then do a Write(), and run this fragment again, the keys for the TH1Fs have appeared. Is there any way to see them without doing a Write()?
If I do an ls() on the TFile before writing, they show up.

This is with 5.08/00b

                          cheers,  Charles.

[quote] It seems as if I need to TFile->Write() on the file before the objects or
even keys appear. [/quote]By definition the key represents things that are on disk, so they indeed should not appear before the first Write.
To see the object in memory that are attached to the TDirectory use
TDirectory::GetList.

Cheers,
Philippe.