Read TMap from a file

Hello!

I have a problem with reading the TMap object from a root file.
Here is the simple code, how I create this TMap and save it to the file:

void TMap_structure() {
    TFile f("filespeed.root","recreate");
    TMap    * tof = new TMap;
    TObjString *key = new TObjString("key!");
    TObjString *val = new TObjString("value!");

    tof->Add(key, val);
    tof->Write("tof");  
    f.Close();
}

But when I am trying to read this TMap from a file, I can’t do it. Here is the code, that I’m using to read TMap from root file:

void Read_root_file_TMap() {
    TMap    * tof = new TMap;
    TFile *f=new TFile("filespeed.root");
    f->GetObject("tof", tof); // Here it just can't find "tof" and stores nothing in tof
    f->Close();
}

As I understood from the TBrowser, the Write() method doesn’t save the TMap structure to the root file, but it rather save all objects (keys and values) from the TMap as independent objects.
So, is this a way to save a TMap in a file and then read it from file and use all its metods (e.g. GetValue, FindObject, etc)?

Best regards, Iurii

_ROOT Version:_6.14/06
_Platform:_macosx64
Compiler: Not Provided

I guess @pcanal can help you.

1 Like

Hi @ibordule,
and welcome to the ROOT forum.
I’m sorry you haven’t heard back from us, I hope you have resolved the issue in the meanwhile.

Writing individual elements of the TMap separately in the TFile is the default behavior, but the TMap::Write docs suggest a way to write a single key instead.

Hope this helps!
Enrico