Error in <TFile::cd>

Dear Rooters

How can I test if a directory in a root file does exist?

Currently I am doing the following:

if (!file->cd("MyName")) {

Although this works fine, sorrowly, root gives me the error message:

Error in TFile::cd: Unknown directory MyName

Since any user of my programm would be confused when such a message
is printed, I would like to know if there is another simple way to test
for the existence of a directory.

Best regards

Hi,TList* keys=file->GetListOfKeys(); TKey* k=(TKey*)keys->FindObject("MyName"); if (k && !strcmp(k->GetClassName(),"TDirectory")) file->cd("MyName");
You simply search the list of the file’s keys for a key with the directory’s name, checking that the key’s object is indeed a TDirectory.

Dear Axel

First, thank you for your fast answer, which I appreciate.

I hope that you don’t mind, but I has hoped that there is a “another simple” and
elegant solution especially for TDirectory such as “FindDirectory”.

For many objects in TFile I am using your solution, but this is a general
and not very elegant “low level” solution, which I need to use whenever there
is no better solution.

I would prefer if there would be a possibility to turn off the output of mkdir.

Best regards

Hi Christian,
you can use this as a shortcut:if (!file->FindKey("MyName")) { file->mkdir("MyName"); file->cd("MyName"); }//if

Hi Axel

Thank you for your second trial. You are right, this solution is much more elegant.
Sorrowly, in my case this solution is not possible since I can have different objects
with the same name, so I have to check for the class :frowning:

Since TDirectory has a special method TDirectory::GetFile(), it would be best if a
similar method TDirectory::GetDirectory() would exist, but this would be a decision
of the root developers.

Best regards