Interference between TSystem::cd() and usage of keys?

Hi ROOT experts!

I wrote some code trying to read histograms from directories inside a root file without using information about the names of directories. Here is a prototype:

writeHist.C:

#include "TFile.h"
#include "TDirectory.h"

#include "TH1.h"
#include "TRandom.h"

void writeHist()
{
  TFile f("f.root","RECREATE");
  TDirectory* dir=f.mkdir("hists");
  dir->cd();
  TH1I hist("hist","hist",100,-5.0,5.0);
  for(int i=0;i<10000;i++)
    hist.Fill(gRandom->Gaus());
  f.Write();
}

readHist.C:

#include <iostream>

#include "TFile.h"
#include "TH1.h"

#include "TNamed.h"

#include "TSystem.h"

#include "TKey.h"
#include "TList.h"

using std::cout;
using std::endl;

void readHist()
{
  TFile* f=new TFile("f.root");

  //gSystem->mkdir("dir");
  //gSystem->cd("dir");

  TList* keyList=f->GetListOfKeys();
  TObjLink* link=keyList->FirstLink();
  while(link){
    TKey* key=(TKey*)link->GetObject();
    TObject* obj=key->ReadObj();

    if(obj->InheritsFrom("TDirectory")){
      TDirectory* dir=(TDirectory*) obj;
      cout<<"Found directory "<<dir->GetName()<<endl;
      TH1* hist=(TH1*)dir->Get("hist");
      if(hist)
        hist->Draw();
      else
        cout<<"hist not found."<<endl;
    }
    link=link->Next();
  }

}

The code runs fine on root 5.34/25. Now when I un-comment the two gSystem lines in readHist.C I got

Error in TFile::GetSize: cannot stat the file f.root
Error in TDirectoryFile::ReadKeys: reading illegal key, exiting after 0 keys
Found directory hists
hist not found.

Now, I tried to replace the f initialization in readHist.C by

the code works again (forgive me for not deleting the pointer I got from ConcatFileName).

So is there requirements I missed, or is this a bug? Thanks a lot.

Hi,

You are right, this is an unintentional limitation introduced many years ago that we need to lift. See sft.its.cern.ch/jira/browse/ROOT-7182

Cheers,
Philippe.

[quote=“pcanal”]Hi,

You are right, this is an unintentional limitation introduced many years ago that we need to lift. See sft.its.cern.ch/jira/browse/ROOT-7182

Cheers,
Philippe.[/quote]

Thanks! I’ve marked this solved.