Write a tree with input from a text file

Hi

What I want to do, is to read a text file which includes x-secs for some processes and then and fill a tree . What I do is this


Double_t x_sec;
tree->Branch("x_sec",&x_sec,"x_sec/D");

#include <fstream>
#include <iostream>
 
string filename = "MyTextFile.txt";
vector<string> input_files;
 
ifstream textfile;
textfile.open(filename.c_str());
if( !textfile.good() ) {
  cerr << "Cannot open the file: \"" << filename+"\"!"<<endl;
  abort();
} 
 
// OK we have the file!
string line("");
while( !textfile.eof() ) {
  line="";
  textfile >> line;
 
   // Do your stuff here! maybe:
   if (line=="") continue;
   if (line== "#") continue;
   input_files.push_back(line);
}

How to take now the string from input_files which of type char and make it of type Double_t in order to write to tree ? (ie pass to and then write it to the x_sec ? )

Thanks in advance!

Hi,

Did you try TTree::ReadFile?

Philippe.

Yes, this worked now!!!

Thanks again Philippe

Would it be possible from this class do the following

read param1 and param2 which are given in the txt like

param1 = value1
param2 = value3
x_sec = cross

and plot the TH2D of x_sec as a func of param1:param2 ??

Thanks again!

see example in $ROOTSYS/tutorials/tree/cernbuild.C

Rene

Hi

I tried the

Tree *mtree;

mtree->Branch("m0", &m0,"m0/D");
mtree->Branch("m12", &m12,"m12/D");

mtree->ReadFile ("file.txt","m0");
mtree->ReadFile("file2.txt,"m12");

but it read correctly only for the 1rst created Branch ie m0 . How can I read multiple files and direct the to different branches ?

Thanks

Hi,

You will need to either use 2 distinct TTree or copy/paste and adapt the code in ReadFile. i.e. ReadFile assumes you are reading all the branches of the TTree.

Cheers,
Philippe.

Ok, thanks for this

Now, how is it possible the value I read from the m0.txt to pass it in an output .root file to be inlcuded in the name, something like

[code]ttree->ReadFile(“file.txt”,m0)

char name[30];
sprinf(name,"%d",m0);

string filename = “…/results/Tree”+name.c_str()+".root";

TFile *savefile = new TFile (“filename”);

[/code]

can this work somehow ?

thanks

Hi,

I am not sure what you tried nor exactly what you mean :slight_smile: but the following might be what you are looking for:void readOneVar(const char *txtfile, const char *varname) { TString filename; filename.Form( "../results/Tree%s.root", varname ); TFile *savefile = new TFile (filename); TTree *tree = new TTree("tree",""); tree->ReadFile(txtfile,varname); tree->GetCurrentFile()->Write(); }

Philippe.

Yes, I think you got the point ie to read a value from a txt file and save it as “extension” to the root file…

Thanks!