Cannot write TDirectoryFile to TFile without creating it in-place

Dear ROOTers,
I am trying to create and fill a TDirectoryFile with some kind of ordered structure (imagine a few subdirectories each containing some histograms), and then pass it along to an analysis framework that will take care of writing it on disk.

When I open the resulting TFile I can see my TDirectoryFile, but unfortunately it’s empty.

I have assembled a small reproducer which highlights the issue:

void test_tdirectory() {
  auto maind = new TDirectoryFile("Main", "Main");
  auto subd1 = maind->mkdir("Sub1", "Sub1");
  subd1->Add(new TH1D("test", "test", 10, 0, 10));


  auto file = std::make_unique<TFile>("test.root", "recreate");
  file->WriteObjectAny(maind, "TDirectoryFile", "maind");


a note: lines 8-9 are there to emulate the framework writing a generic object to disk, on which I have no control. Also, I don’t have access to the underlying TFile since the framework doesn’t expose it to the user. I tried replacing WriteObjectAny with WriteTObject or similar alternatives, with no joy.

I suspect that when writing a TDirectoryFile, its contents are not recursively written, which is what I am expecting.

Is there some workaround to get the full directory structure to disk without calling mkdir on the TFile pointer directly?


ROOT Version: 6.28/04
Platform: Arch linux
Compiler: gcc (GCC) 13.2.1 20230801

Add a directory to a TFile was designed to be done via the mkdir function and no provision was made to work-around it. In particular WriteObjectAny does not handle the TDirectoryFile in any special way … which it would need to to make it a proper directory.

My guess is that the best is that the framework allows (or maybe it already does) to create directories in the TFile (if not it needs to be upgraded to).


Alternative is to emulate the behavior with a different collection (eg. TFolder) or by using a (probably not sanctioned and not reliable) back way to get to the TFile pointer.

Got it. I’ll keep looking for a workaround then. thanks.


This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.