TFile and TKey

Header Files

The following may be needed if not using CINT Shortcuts #include "TFile.h" #include "TKey.h"

Description

ROOT files are organised into directories in much the same way as HBOOK files are. Within each directory are a set of objects or more precisely their data members. Random access to each is provided via an associated TKey object. TKeys have names and objects retrieved via these names.

TFile objects are used to access HROOT files. To create a TFile object corresponding to a new file called "Event.root" (.root is the preferred extension):-

TFile *MyFile = new TFile("Event.root","NEW"); Other options are CREATE (=NEW), RECREATE (i.e. replace), UPDATE and READ. To check that file was successfully opened:- if ( MyFile->IsOpen() ) printf("File opened successfully\n"; Once a TFile object has been created it becomes the default file for all I/O. This default is held in the global variable gFile, which can be updated at any time to change the default, e.g.:-
gFile = MyFile;

As explained in ROOT I/O, once a file has been opened, objects can be written by sending them their Write message, e.g.:-

MyObject->Write("MyObject_1");
writes a copy of MyObject to the current directory of the current file with the named key "MyObject_1". In a similar way:-
MyObject->Read("MyObject_1");
can be used to read it back into an existing object. Alternatively the TFile object can be asked to find and create it:-
MyClass *MyObject = (MyClass *) MyFile.Get("MyObject_1"); 
Sending a Tfile its Write message:-
MyFile->Write();
results in all objects currently in memory being written out. Each is asked its name (the GetName message) which is used as its key. For objects that have no name the object's class name is used (with a version number to ensure the key is unique). Having finished with a TFile, its Close message should be sent:-
MyFile->Close();
although ROOT will close all open files when the session ends.

Example Use in MINFast

The class MINFile HasA TFile object.

For more information see Reading ROOT Class Info.


Go Back to the The ROOT Crib Top Page


If you have any comments about this page please send them to Nick West