Re: Reading strings from a tree?

From: Pasha Murat (murat@cdfsga.fnal.gov)
Date: Tue Jul 28 1998 - 06:31:48 MEST


stefan kluth writes:
 > 
 > Hello,
 > 
 > I try to write strings into a tree (and to read them back of course!). I
 > seem to be able to write strings ok, but I can't read them back. Here is
 > what I do:
 > 
 > ...
 > 
 >   TFile myfile( "treetest.root", "RECREATE" );
 >   TTree* tree = new TTree( "tree", "ROOT test tree" );
 >   char* ach;
 >   TBranch* brach= tree->Branch( "ach", (void*)ach, "ach/C", 8000 );
 > 
 > ... now loop and fill ach with different strings, works ok. 
 > 
 > Then I do in root (2.00/08):
 > 
 > root [0] #include <iostream.h>
 > root [1] TFile myfile( "treetest.root");
 > root [2] myfile.ls();
 > TFile**         treetest.root
 >  TFile*         treetest.root
 >   KEY: TTree    tree;1 ROOT test tree
 > root [3] TBranch *brach  = tree.GetBranch("ach");
 > root [4] char* ach;
 > root [5] brach->SetAddress(ach);
 > root [6] tree.GetEvent(3);
 > root [7] cout << ach << endl; 
 > 
 > root [8]
 > 
 > 
 > So, somehow the strings stored in the tree branch "ach" don't get assigned
 > to the char* ach. 
 > 
 > Any ideas as what am I doing wrong here?
 > 


You may try to define the tree variable when you're reading the data back. 
Find below the example of macro which does what (I believe) you need.

						regards, pasha.

-------------------------------------------- test.C
int test(int mode) {
  char*  ach = new char[100];
  if (mode == 0) {
				// writing

    TFile*  myfile = new TFile   ("test.root", "RECREATE" );
    TTree*   tree  = new TTree   ("Tree", "ROOT test tree" );
    TBranch* brach = tree->Branch("ach", (void*)ach, "ach/C", 8000 );

    for (int i=0; i<99; i++) {
      for (int j=0; j<i; j++) ach[j] = 48+i;
      ach[i] = 0;
      tree->Fill();
    }
    delete [] ach;
    tree->Write();
    delete myfile;
  }
  else {
				// reading

    TFile* myfile = new TFile( "test.root");
    TTree* tree = (TTree* ) myfile->Get("Tree");
    TBranch *brach  = tree->GetBranch("ach");
    brach->SetAddress((void*)ach);
 
    for (int i=1; i<10; i++) {
      ach[0] = 0C;
      tree->GetEvent(i);
      cout << ach << endl;
    }
    delete myfile;
  }
  return 0;
}
--------------------------------------------------
root [14] .L test.C      
root [15] int rc;         
root [16] rc = test(0)
(int)0
root [17] rc = test(1);
1
22
333
4444
55555
666666
7777777
88888888
999999999
root [18] 



This archive was generated by hypermail 2b29 : Tue Jan 04 2000 - 00:34:35 MET