Reading Objects From Disk

Hi there,

I wanted to know if there is a method to persistently keep objects in memory after reading from a TFile, so that the TFile can be closed.

As an example, my current code is as below (there is a global TChain called T1). When I try to get the file (in GetCutList) after having saved it (with SaveCutList), the routine crashes on the line where I try to use TEventList::GetN() immediately after closing the file.

void SaveCutList(TCut cuttosave, bool append, string filename)  {
  TEventList * eventsfrom = new TEventList("eventsfrom", "eventsfrom");
  T1->Draw(">>eventsfrom", cuttosave);
  string openopt = append ? "UPDATE": "RECREATE";
  TFile fs(filename.c_str(), openopt.c_str());
  fs.SetCompressionLevel(0);
  eventsfrom->Write(cuttosave.GetName(),TObject::kOverwrite);
  fs.Close();
  delete eventsfrom;
}


TEventList * GetCutList(TCut cuttoget, string filename)  {
  TEventList * returnlist(0);
  TFile * fs = new TFile(filename.c_str(), "READ");
  if (fs->IsZombie()) {
      cout <<"Could not find file: " << filename <<endl;
      return returnlist;
  }
  TList * klist = fs->GetListOfKeys();
  if (klist->Contains(cuttoget.GetName())) {
    returnlist = new TEventList("eventsfrom","eventsfrom");
    returnlist->Read(cuttoget.GetName());
  }
  else cout << "Could not find list!" << endl;
  cout << "Try 1 " << returnlist->GetN() << endl;
  fs->Close();
  cout << "Try 2 " << returnlist->GetN() << endl;
  return returnlist;
}

Any help would be appreciated.

Hi,

You can explicit remove the object from the TDirectory (and/or TFile) list of live object:fs->GetList()->Remove(returnlist);

Cheers,
Philippe.

Hi Philippe,

Thanks for the input, however if I adjust the end of GetCutEventList() appropriately such that it reads:

  cout << "Try 1 " << returnlist->GetN() << endl;
  fs->GetList()->Remove(returnlist);
  fs->Close();
  cout << "Try 2 " << returnlist->GetN() << endl;
  return returnlist;

I still get a crash on the line that reads cout << “Try 2”… do you have any further thoughts? I won’t to close the TFile, yet have the object from the file remain in memory.

Thanks again.

Hi,

Can you send me a complete running example reproducing the problem?

Thanks,
Philippe.

Hi Philippe,

Sorry, I can get it to work with the GetList()->Remove(object) line you suggested now, I can’t explain why it didn’t work originally.

Thanks for your help,

Andy