Re: Question about TFile

From: Rene Brun (Rene.Brun@cern.ch)
Date: Thu Oct 30 1997 - 08:40:25 MET


Reid D Rivenburgh wrote:
> 
> Hi,
> 
> I have a question about TFile.  In our application we're developing a
> class that will act as a sort of database, having a convenient
> interface for persistently storing and retrieving ROOT objects.  One
> of its members will be a TFile, which will do most of the work of
> storing and retrieving.  My question, then, is how will this class
> (and possibly multiple instances of it) having a TFile interere with
> other TFiles created by the main program?  In most ROOT examples I've
> seen and in code I've written, there's only ever one TFile in
> existence at a time.  The TROOT class seems to maintain a "current
> TFile" for when an object calls its Write() method.  When I create one
> of these database objects, though, I probably don't want its TFile to
> become the current one.  And, I don't want the database object to
> write every object in memory to its TFile, just the ones I tell it to
> write.  Is there any hope of achieving this, or is it not the intended
> use for a TFile?  Is there a better approach?  It's a bit confusing
> (though I did read an old roottalk thread about TFiles, and that
> helped some).
> 

You can have as many TFile objects as you want. The only thing
to remember is that histograms and Trees are created by default
in the current directory. When you open a TFile, the current directory
is automatically changed to this file. You can change the current
directory with TFile::cd().
When filling Trees, it is not necessary to change the current directory
to the file associated with this Tree, ROOT will do it automatically
for you. However, when you write the Tree header, you MUST cd
to the right file. 
Do not worry! ROOT writes on the data base only objects for which
you do object.Write.
Here is an example of code dealing with 3 files.

Rene Brun

//--------------------example with multiple TFile objects---------
   TFile f1("f1.root","recreate");
   TH1F h1(...
   TTree t1(...

   TFile f2("f2.root","recreate");
   TH1F h2(...
   TTree t2(...

   TFile f3("f3.root","recreate");
   TH1F h3(...
   TTree t3(...

   for (int i=0;i<1000;i++) {
      h1.Fill(..
      t1.Fill(...
      h2.Fill(..
      t2.Fill(...
      h3.Fill(..
      t3.Fill(...
   }
   f1.cd();   h1.Write(); t1.Write();
   f2.cd();   h2.Write(); t2.Write();
   f3.cd();   h3.Write(); t3.Write();

//-----alternative
   TFile f1("f1.root","recreate");
   TFile f2("f2.root","recreate");
   TFile f3("f3.root","recreate");
   f1.cd();
   TH1F h1(...
   TTree t1(...
   f2.cd();
   TH1F h2(...
   TTree t2(...
   f3.cd();
   TH1F h3(...
   TTree t3(...
etc..



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