#include #include #include #include #include #include #include "TTree.h" #include "TFile.h" //class ifstream; void txt2tree( char* infilename, char* outfilename ) { // Macro to read data from an ascii file and create a root file with a TTree // gROOT->Reset(); // open file ifstream infile; infile.open(infilename); // read first non-empty line std::string line; line.clear(); while (line.size() == 0) { getline(infile,line,'\n'); } // find variable names and remove whitespaces std::string::size_type pos = 0; std::vector var_names; while ( pos < line.length() ) { pos=line.find(" "); if ( pos != 0 ) var_names.push_back( line.substr(0,pos) ); line = line.substr(pos+1,line.length()); // std::cout << "line="< 0) { var_names.push_back(line); } // std::cout << "last line="<< line << std::endl; // declare vector to contain floating point variables and initialize to zero std::vector variables; variables.resize(var_names.size(), 0); // create a TTree TTree *tree = new TTree("T",infilename); // create tree branches for ( unsigned int i=0; iBranch(var_names[i].c_str(),&(variables[i]),format.c_str()); } // fill the tree from the values in ASCII file unsigned int i=0; while ( !infile.eof() ) { infile >> variables[i]; i++; // reset i and write variables to tree if ( i == var_names.size() ) { // for ( unsigned int j=0; jFill(); i=0; } } // create a new ROOT file and write TTree into it TFile *outfile = new TFile(outfilename,"RECREATE"); tree->Write(); tree->Print(); // close files infile.close(); outfile->Close(); return; } int main(int argc, char* argv[]) { if (argc == 2 && std::string(argv[1])=="-h") { std::cout << std::endl; std::cout << "TEXT2TREE -- RG,9 Oct.2009" << std::endl; std::cout << std::endl; std::cout << "txt2tree reads formatted data from an ASCII file and writes it as a ROOT TTree" << std::endl; std::cout << "Input file format: " << std::endl; std::cout << "First line: variable names separated by one or more spaces" << std::endl; std::cout << "Other lines: variable values in columns (as many as variable names)" << std::endl; std::cout << std::endl; std::cout << "usage: txt2tree [input file] [root file]" << std::endl; std::cout << std::endl; } else if (argc == 3) { std::cout << std::endl; std::cout << "txt2tree: reading ASCII file " << argv[1] << " and writing ROOT file " << argv[2] << std::endl; std::cout << std::endl; txt2tree( argv[1], argv[2] ); } else { std::cout << "ERROR: two arguments required; do txt2tree -h" << std::endl; return 1; } return 0; }