# ROOT files

In ROOT you can save and read objects from ROOT files. With a ROOT file you can make the created objects “persistent”. When reading the ROOT file back, the object is reconstructed in the memory.

ROOT files also often contain tress ( TTree , see → Trees), a typical data container used for example by all LHC (Large Hadron Collider) experiments.

## Working with ROOT files

A ROOT file, this is a TFile object, is like a UNIX file directory. It can contain directories and objects organized in unlimited number of levels. A ROOT file is stored in machine independent format (ASCII, IEEE floating point, Big Endian byte ordering).

### Creating a ROOT file

• Use the TFile constructor for creating a ROOT file. A ROOT file uses the .root extension.

The following options are available:

• CREATE: Creates a ROOT file.

• NEW: Same as CREATE.

• RECREATE: Replaces the ROOT file.

• UPDATE: Updates the ROOT file.

• READ: Opens an existing ROOT file for reading.

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 (see → ROOT classes, data types and global variables), which can be updated at any time to change the default.

Current directory

When you create a TFile object, it becomes the current directory. Therefore, the last ROOT file to be opened is always the current directory.
Check the current directory as follows:

In this case, the current directory is the ROOT session (Rint).

When you create a TFile object, the ROOT file becomes the current directory.

### Checking whether a ROOT file is open

• Use TFile::IsOpen() to check whether the ROOT file was successfully opened.

Note

You can also check whether the ROOT file is correctly opened by:

### Writing ROOT files

You can save any object, for example canvases, histograms or trees, in a ROOT file.

To write objects to a ROOT file, the objects must be open.

Example

A copy of MyObject is written to the current directory of the current ROOT file with the named key MyObject_1:

If MyObject does not inherit from TClass , you can use

Example

This example creates 15 histograms, fills each histogram with 1000 entries from a Gaussian distribution, and writes them to a ROOT file.

The ROOT file is saved by default in the current working directory.

### Closing a ROOT file

ROOT will automatically close any ROOT files still open when the session ends.

• Use delete to delete the TFile object.

### Retrieving objects from a ROOT file

• Use the GetObject() method to retrieve the objects from a ROOT file.

Example

From the ROOT file hsimple.root (see → First steps with ROOT), the histogram hpx;1 is retrieved.

In detail, the following happens when executing GetObject():

• The key with name hpx;1 is found in the list of keys.

• A TBuffer object is created.

• The buffer is read from the ROOT file.

• An empty object is created by calling the default constructor for the class referenced in TKey .

• The Streamer() method is called for this new object.

In case there is an object with multiple cycles, you can pick a particular cycle with a name like hpx; (for example hpx;2).

You can also directly access the keys, for example when the names of the objects contained in the ROOT file are not known or when a long series of objects needs to be read sequentially.

Example

This example illustrates how to loop over all keys of a ROOT file.

Crash while reading and writing the ROOT file

If ROOT is not properly terminated, the file directory may not be written at the end of the ROOT file. Next time this ROOT file is used, ROOT will automatically detect this abnormal termination and will recover the directory by scanning sequentially the list of keys in the ROOT file. If the ROOT file has been opened in UPDATE mode, the recovered directory will be automatically written to the ROOT file. This automatic recovery procedure is possible because of redundant information written to the ROOT file.
In case you write large trees (see also → Trees), you may have large buffers in memory. In case of a job crash, you may loose a lot of data. Therefore, it recommended to use the auto save method TTree::AutoSave.

### Reading histograms from a ROOT file

• Use the Get() method to read histograms from a ROOT file.

Example

The Event class is defined in $ROOTSYS/test/Event.h. It inherits from TObject . Example A simple example of a class with several data members. The Event class is added to the dictionary with rootcling. The EventDict.cxx file contains the automatically generated Streamer for Event. When writing an Event object, TClass::WriteBuffer() is called. TClass::WriteBufferwrites the current version number of the Event class, and its contents into the buffer R__b. The Streamer calls TClass::ReadBuffer() when reading an Event object. The TClass::ReadBufferRead() method reads the information from buffer R__b into the Event object. ### Transient data members To prevent a data item from being written to the file, insert a ! as the first character in the comment (//). It tells ROOT not to store this data item in a ROOT file when saving the class. Example ### The pointer to objects The string -> in the comment of the members *fH and *fTracks tells the automatic Streamer to assume that these point to valid objects and that the Streamer of the objects can be called, instead of the more expensive R__b << fH. Note that there is no check for the validity of the pointer value. In particular, if the pointer points, directly or indirectly, back to the current object, this leads to an infinite recursion and the abrupt end of the process. Example ### Variable length array When the Streamer finds a pointer to a simple type, it assumes it is an array. Somehow it needs to know how many elements are in the array in order to allocate enough space in the buffer and write out the appropriate number of elements. This is done in the class definition. Example The fClosestDistance array is defined as a pointer of floating point numbers. A comment mark (//), and the number in square brackets tell the Streamer the length of the array for this object. In general the syntax is: The length cannot be an expression. If a variable is used, it must be an integer data element of the class. It must be defined before it is used or in a base class. The same notation applies to variable length arrays of objects and variable length arrays of pointers to objects. ### Double32_t Mathematical operations very often require double precision, but when storing, single precision is usually sufficient. For this purpose the typedef Double32_t is supported, which is stored in memory as double and on disk as float or integer. The actual size on disk (before compression) is determined by the parameter next to the data element declaration. Example If the comment is absent or does not contain min, max, nbits, the member is saved as a float. If min and max are present, they are saved with 32 bits precision. min and max can be explicit values or expressions of values known to rootlcing (for example pi). If nbits is present, the member is saved as integer with nbits bits precision. For more details, see the I/O-tutorials double32.C. ### Preventing splitting If you want to prevent a data item from being split when you write it to a tree, add || directly after the comment. This is only useful for object data members. Example ### Streamers with special additions Usually, a Streamer is generated by rootcling. However, you can also create your own Streamer. There are two reasons why you should create your own streamer: 1. If you have a non-persistent data item that you want to initialize to a value depending on the data items you read. 2. If you need to handle or schema evolution yourself. Example First, you need to tell rootcling not to build a Streamer. The input to the rootcling command (in the makefile) is a list of classes in a LinkDef.h file. For example, the list of classes for Event is listed in $ROOTSYS/test/EventLinkDef.h. - at the end of the class name indicates rootcling not to generate a Streamer. In this example can see that the Event class is the only one for which rootcling is instructed not to generate a Streamer.

The + sign indicates rootcling to use the Streamer system.

The following is an example of a customized Streamer for Event. The Streamer takes a
TBuffer as a parameter, and first checks to see if this is a case of reading or writing the buffer.

Example

### Writing objects

A Streamer breaks the objects into data members and writes them to a buffer. It does not write the buffer to a file, but simply fills a buffer with bytes representing the object. This allows, for example, to write the buffer to a file. For example, you can write it to a socket to send it over the network.

A buffer is written to a file by loading the dictionary for a class before an object of that type can be stored.

The TObject::Write() method does the following:

• Creates a TKey object in the current directory.
• Creates a TBuffer object, which is part of the newly created TKey .
• Fills the TBuffer with a call to the class::Streamer method.
• Creates a second buffer for compression, if needed.
• Reserves space by scanning the TFree list. At this point, the size of the buffer is known.
• Writes the buffer to the file.
• Releases the TBuffer part of the key.

This means that the TObject::Write() calls the Streamer method of the class to build the buffer. The buffer is in the key and the key is written to disk. Once written to disk, the memory consumed by the buffer part is released. The key part of the TKey is kept. The key consumes about 60 bytes, whereas the buffer, since it contains the object data, can be very large.

### Ignoring object Streamers

A class can ignore the TObject Streamer with the MyClass->Class::IgnoreObjectStreamer() method. When the kIgnoreTObjectStreamerbit class is set (by calling the IgnoreTObjectStreamer() method), the automatically generated Streamer does not call TObject::Streamer, and the TObject part of the class is not streamed to the file. This is useful in case you do not use the TObject fBits and fUniqueIDdata members. You gain space on the file, and you do not loose functionality if you do not use the fBits and fUniqueID.

### Streaming a TClonesArray

When writing a TClonesArray , it bypasses by default the Streamer of the member class and uses a more efficient internal mechanism to write the members to the file.

You can override the default and specify that the member class Streamer is used by setting the TClonesArray::BypassStreamer bit to false:

When the kBypassStreamer bit is set, the automatically generated Streamer can call directly the TClass::WriteBuffer method. Bypassing the Streamer improves the performance when writing or reading the objects in the TClonesArray .

However, the drawback is when a TClonesArray is written with split=0 bypassing the Streamer, the StreamerInfo of the class in the array being optimized, one cannot later use the TClonesArray . with split > 0.

For example, there is a problem with the following scenario: a class Foo has a TClonesArray of Bar objects the Foo object is written with split=0 to tree T1. In this case the StreamerInfo for the class Bar is created in optimized mode in such a way that data members of the same type are written as an array improving the I/O performance. In a new program, T1 is read and a new tree T2 is created with the object Foo in split > 1.

When the T2branch is created, the StreamerInfo for the class Bar is created with no optimization (mandatory for the split mode). The optimized Bar StreamerInfo is going to be used to read the TClonesArray in T1. The result are Bar objects with data member values not in the right sequence. The solution to this problem is to call BypassStreamer(kFALSE) for the % include ref class=”TClonesArray” %}. In this case, the normal Bar::Streamer function is called. The Bar::Streamer function works independently if the Bar StreamerInfo has been generated in optimized mode or not.

## Remotely accessing a ROOT file

You can remotely access ROOT files on the base of the protocol URL.

You can read and write a ROOT file over the net by using the TFile::Open() method.

Example

Simple session:

ls() lists what is in the ROOT file.

## XML interface

You can save a canvas to an XML file, that is a file.xml file instead of a file.root. XML files have no advantages over the normal ROOT files, except that the information in these files can be edited with a normal text editor.

XML files should only be used for small amounts of data, typically histogram files, images, geometries, calibrations. The XML file is created in memory before it is stored on disk. As for normal ROOT files, XML files use the same I/O mechanism that the ROOT/Cling dictionary uses. Any class that has a dictionary can be stored in XML format. XML files do not support subdirectories or trees.

To create an XML file, specify a filename with an .xml extension when calling TFile::Open(). TFile::Open() recognizes that you are trying to open an XML file and returns a TXMLFile object. When a XML file is open in write mode, you can use TObject::Write() to write an object into the XML file.

Example