Convert a root file to a readable txt file

Hi Everyone,
I want to convert my root file to a txt file. I followed the instruction extract data to txt file.
My cxx file is like this:

void root2txt(const char *fname = "4lyr1.root",
          const char *nname = "Coincidences")
{
  if (!fname || !(*fname) || !nname || !(*nname)) return; // just a precaution
  
  TFile *f = TFile::Open(fname, "READ");
  if ((!f) || f->IsZombie()) { delete f; return; } // just a precaution
  
  TTree *t; f->GetObject(nname, t);
  if (!t) { delete f; return; } // just a precaution
  

  t->SetScanField(0);
  t->Scan("*");

  t->SaveAs("modify.txt");
  // t->SaveAs(TString::Format("%s.xml", nname));
  
  delete f; // no longer needed (automatically deletes "t")
}

I generated the txt file successfully, but I couldn’t read it. When I opened the txt file in my laptop, it just shows:
{
//========= Macro generated from object: Coincidences/The root tree for coincidences
//========= by ROOT version6.18/04
//Primitive: Coincidences/The root tree for coincidences. You must implement TTree::SavePrimitive
}
These are not the data that I want. Does anyone can help? How can I generate a readable txt file?
Thank you very much!

Use:

((TTreePlayer*)(t->GetPlayer()))->SetScanRedirect(true);
((TTreePlayer*)(t->GetPlayer()))->SetScanFileName("modify.txt"); 

Thank you for reply! Do you means add this two lines in the code or do I need to delete something?
I delete

  t->SetScanField(0);
  t->Scan("*");
  t->SaveAs("modify.txt");

In this way, there are nothing in the txt file. Sorry I am new to ROOT.

You need to drop the

t->SaveAs("modify.txt");

which overwrite the file with something you don’t want.

Thank you! This works!

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