Checking existance of object in file

Hi rooters,

I would like to check for the existance of an object with a known name in a file so that I can create it if it doesn’t exist and Get() it if it does. I’ve been struggling with keys and such but I haven’t succeeded.

TFile outfile(filename,"update");
if (somehow check object exists)
histopointer = (TH1F*)outfile.Get(histoname);
histopointer = new TH1F(histoname, "title", num_bins, down, up);

Please help with explicit code.

Many thanks,

outfile.Findkey(histoname) (in TDirectory)


Hi Rene,

Please help, I’m still struggling.

I’ve attached my code. I have not been able to cast my variable
to the correct type for Findkey(). I get the folloing message:

[quote]no matching function for call to `TFile::Findkey(const char*)’
which naively seems fine when compared with the declaration:

[quote]virtual TKey* FindKey(const char* keyname) const
Also, I am not sure how to use this in a boolean condition. Do you mean something like the following?

    TKey *key = outfile.Findkey(histoname);
    if (key == 0)

Thanks again,
project.tar (30 KB)

Replace the line
TKey *key = outfile.Findkey(&*histoname);

TKey *key = outfile.FindKey(histoname);


Hi Rene,

Thank you for your promp reply. What you suggest is actually the first thing that I tried. When I make the replacement I get the following error.

If this works for you and not for me, then I guess it is something to do with my system. I am using root version 4.00/08 on RHEL3 with gcc version 3.2.3.

Do you have any suggestions for me?


Please check carefully my reply
Findkey is not the same as FindKey

Anyhow, just look at TDirectory::FindKey to see the signature


Hi Rene,

Thank you, it works. I apologise for my silliness.