ROOT files
Learning objectives
After completing this chapter, you should be able to:
- Understand the structure and purpose of ROOT files.
- Open existing ROOT files.
- Inspect the objects stored within a file.
- Retrieve objects using their names.
- Create ROOT files and store objects.
- Organise objects into directories.
- Understand object ownership and file lifetime.
- Identify common file-related errors.
What is a ROOT file?
A ROOT file is a binary file designed to store scientific data and C++ objects in a persistent form.
ROOT files typically use the .root extension and can
contain various types of objects, including:
- Histograms
- Trees and branches
- Graphs
- Mathematical functions
- Directories
- User-defined objects with appropriate ROOT dictionaries
Unlike a conventional text file, a ROOT file preserves information about the types and properties of the stored objects.
ROOT also supports data compression and efficient access to large scientific datasets.
Persistent storage
Objects created during program execution normally exist in memory.
Persistent storage allows these objects to be saved to a file and reconstructed during a later program execution.
ROOT provides mechanisms for converting objects into a representation suitable for storage and reconstructing them when needed.
This process is known as serialisation.
Structure of a ROOT file
A ROOT file can be organised into a hierarchical directory structure, similar to a conventional file system.
Each directory can contain objects and additional subdirectories.
flowchart TD
A["events.root"] --> B["Events"]
A --> C["Histograms"]
A --> D["Metadata"]
B --> E["collisionTree : TTree"]
C --> F["h_pt : TH1D"]
C --> G["h_eta : TH1D"]
C --> H["h_phi : TH1D"]
D --> I["description : TNamed"]
classDef file fill:#4477aa20,stroke:#4477aa
classDef directory fill:#64748b20,stroke:#64748b
classDef object fill:#0d948820,stroke:#0d9488
class A file
class B,C,D directory
class E,F,G,H,I object
Objects and directories
The structure above is illustrative.
ROOT files do not necessarily contain directories, trees or histograms with these particular names.
The actual structure depends on how the file was created.
The TFile class
The TFile class provides the primary interface for
reading and writing ROOT files.
#include <TFile.h>
A TFile object represents an open ROOT file and
provides methods for accessing its contents.
ROOT files can be opened using either the constructor
or the static TFile::Open() method.
Using the constructor
TFile file("events.root", "READ");
Using the Open method
TFile* file = TFile::Open("events.root", "READ");
The second approach returns a pointer to a TFile
object.
Static methods
A static method belongs to a class rather than to a particular instance of that class.
Therefore, TFile::Open() can be called without
first creating a TFile object.
The scope resolution operator :: identifies
the class to which the method belongs.
File opening modes
The second argument specifies how the file should be accessed.
| Mode | Description |
|---|---|
READ |
Open an existing file for reading. |
CREATE |
Create a new file. Fail if it already exists. |
NEW |
Equivalent to CREATE. |
RECREATE |
Create a new file, replacing an existing file. |
UPDATE |
Open an existing file for modification, or create it if necessary. |
Overwriting existing files
Opening a file using RECREATE replaces its
previous contents.
TFile file("events.root", "RECREATE");
If events.root already exists, its original
contents will be lost.
Always use a separate output file when processing experimental input data.
Checking whether a file was opened successfully
A file may fail to open for several reasons:
- The specified file does not exist.
- The file path is incorrect.
- The file is corrupted.
- The user does not have the necessary permissions.
- The file is not a valid ROOT file.
ROOT provides the IsZombie() method to identify
objects that could not be constructed correctly.
TFile file("events.root", "READ");
if (file.IsZombie())
{
std::cerr << "Failed to open file.\n";
return;
}
TFile* file = TFile::Open("events.root", "READ");
if (!file || file->IsZombie())
{
std::cerr << "Failed to open file.\n";
delete file;
return;
}
Null pointers
TFile::Open() may return a null pointer if
the file cannot be opened.
Always check the pointer before accessing its methods.
The logical OR operator || uses short-circuit
evaluation. If !file is true, the expression
file->IsZombie() is not evaluated.
Inspecting a ROOT file
Before processing a scientific dataset, it is important to understand how its contents are organised.
Opening a file interactively
A ROOT file can be opened directly from the terminal:
root -l events.root
ROOT opens the file and makes it accessible through the interactive environment.
To list the objects in the current ROOT directory:
.ls
Alternatively, a file can be opened explicitly:
TFile* file = TFile::Open("events.root");
file->ls();
Understanding the output
An illustrative output might look like this:
TFile** events.root
TFile* events.root
KEY: TTree collisionTree;1 Collision events
KEY: TH1D h_pt;1 Transverse momentum
KEY: TH1D h_eta;1 Pseudorapidity
The output contains information about the stored objects.
| Component | Meaning |
|---|---|
TTree |
Class of the stored object |
collisionTree |
Object name |
;1 |
Key cycle number |
Collision events |
Object title |
The object name is used to retrieve the object from the file.
The ROOT object browser
ROOT provides a graphical browser for inspecting files, directories and stored objects.
Start ROOT and execute:
new TBrowser();
The browser allows you to:
- Navigate through ROOT files.
- Explore directories.
- Inspect trees and branches.
- Display stored histograms.
- Examine graphical objects.
Explore before analysing
Before writing an analysis macro, inspect the input ROOT file.
Identify the names and types of the objects that are relevant to your analysis.
Never assume that a dataset contains a particular tree or branch without checking.
Retrieving objects from a ROOT file
Objects are retrieved using their names.
The Get() method provides access to objects
stored in a ROOT directory.
Retrieving a histogram
#include <TFile.h>
#include <TH1D.h>
void read_histogram()
{
TFile file("events.root", "READ");
if (file.IsZombie())
{
return;
}
TH1D* hist = file.Get<TH1D>("h_pt");
if (!hist)
{
std::cerr << "Histogram not found "
<< "or incompatible type.\n";
return;
}
std::cout << hist->GetEntries() << '\n';
}
The template argument <TH1D> specifies the
expected type of the retrieved object.
Retrieving a tree
#include <TFile.h>
#include <TTree.h>
void read_tree()
{
TFile file("events.root", "READ");
if (file.IsZombie())
{
return;
}
TTree* tree = file.Get<TTree>("collisionTree");
if (!tree)
{
std::cerr << "Tree not found.\n";
return;
}
std::cout << "Number of entries: "
<< tree->GetEntries()
<< '\n';
}
Trees and their internal structure will be discussed in detail in the following chapter.
Retrieving objects from subdirectories
If an object is stored inside a directory, its path can be specified relative to the file.
TH1D* hist = file.Get<TH1D>("Histograms/h_pt");
Alternatively, the directory can be retrieved first:
TDirectory* dir = file.GetDirectory("Histograms");
if (dir)
{
TH1D* hist = dir->Get<TH1D>("h_pt");
}
Object names are case-sensitive
The following names refer to different objects:
h_ptH_pth_PT
Always use the exact name stored in the file.
ROOT keys
Objects stored in a ROOT file are associated with keys.
A key contains information about a stored object, including its:
- Name
- Class name
- Title
- Cycle number
- Storage-related information
ROOT represents these keys using the TKey class.
Listing keys programmatically
#include <TFile.h>
#include <TKey.h>
#include <TList.h>
#include <iostream>
void inspect_file()
{
TFile file("events.root", "READ");
if (file.IsZombie())
{
return;
}
TIter next(file.GetListOfKeys());
while (TObject* object = next())
{
TKey* key = static_cast<TKey*>(object);
std::cout << "Name: "
<< key->GetName()
<< ", Class: "
<< key->GetClassName()
<< ", Cycle: "
<< key->GetCycle()
<< '\n';
}
}
This example lists the keys stored in the top-level directory of the file.
Subdirectories must be inspected separately.
Keys and objects
Inspecting a key does not require reconstructing the complete stored object.
This makes keys useful for examining the contents of a file before loading its data.
Key cycles
ROOT can store multiple versions of an object under the same name.
For example:
h_pt;1
h_pt;2
h_pt;3
These entries represent different key cycles associated with the same object name.
By default, retrieving an object by name normally accesses the highest available cycle.
TH1D* hist = file.Get<TH1D>("h_pt");
A particular cycle can also be requested:
TH1D* hist = file.Get<TH1D>("h_pt;1");
Key cycles are not separate observations
Multiple key cycles generally represent separately written versions of an object.
They should not be confused with entries
in a TTree or bins in a histogram.
Creating a ROOT file
ROOT files can also be created to store the results of scientific analyses.
The following example creates a ROOT file containing a one-dimensional histogram.
#include <TFile.h>
#include <TH1D.h>
#include <iostream>
void create_file()
{
TFile file("results.root", "RECREATE");
if (file.IsZombie())
{
std::cerr << "Cannot create output file.\n";
return;
}
TH1D hist(
"h_example",
"Example histogram;x;Counts",
10, 0.0, 10.0
);
hist.Fill(2.5);
hist.Fill(4.2);
hist.Fill(4.5);
hist.Fill(7.1);
hist.Write();
}
Execute the macro:
root -l -b -q create_file.C
The resulting results.root file contains
the histogram and its associated information.
The file can subsequently be opened and the histogram retrieved in another ROOT session.
Writing objects
The Write() method writes an object into
the current ROOT directory.
hist.Write();
An object can also be written using a different name:
hist.Write("momentum_distribution");
Alternatively, an object can be written explicitly into a particular directory or file:
file.WriteObject(&hist, "h_example");
The second approach makes the destination of the object explicit.
Use meaningful object names
Prefer descriptive names that identify the physical quantity represented by the object.
Examples:
h_transverse_momentumh_pseudorapidityh_azimuthal_angleh_event_multiplicity
Consistent naming conventions make scientific datasets easier to navigate.
Directories and the current ROOT directory
ROOT files can contain directories represented
by the TDirectory class.
Directories are useful for separating objects associated with different analysis stages, particle species or selection criteria.
Creating directories
TFile file("results.root", "RECREATE");
TDirectory* histDir = file.mkdir("Histograms");
TDirectory* metaDir = file.mkdir("Metadata");
Changing the current directory
histDir->cd();
The cd() method changes the current ROOT
directory.
ROOT provides the global variable gDirectory,
which refers to the current directory.
gDirectory->pwd();
Writing objects into directories
#include <TFile.h>
#include <TDirectory.h>
#include <TH1D.h>
void organised_output()
{
TFile file("results.root", "RECREATE");
if (file.IsZombie())
{
return;
}
TDirectory* dir = file.mkdir("Histograms");
if (!dir)
{
return;
}
TH1D h_pt("h_pt", "Momentum", 100, 0, 10);
TH1D h_eta("h_eta", "Pseudorapidity", 100, -5, 5);
h_pt.Fill(1.5);
h_eta.Fill(0.3);
dir->WriteObject(&h_pt, "h_pt");
dir->WriteObject(&h_eta, "h_eta");
}
The resulting file has the following structure:
results.root
└── Histograms/
├── h_pt
└── h_eta
ROOT directories and system directories
The current ROOT directory is not the same as the current working directory of the operating system.
gDirectory refers to ROOT's internal
directory structure.
Updating existing ROOT files
The UPDATE mode allows new objects to be
written into an existing ROOT file.
TFile file("results.root", "UPDATE");
A new object can then be added:
TH1D hist("h_new", "New distribution", 50, 0, 5);
hist.Fill(2.1);
hist.Write();
Writing an object under an existing name may create an additional key cycle.
To replace the existing key instead, use:
hist.Write("h_new", TObject::kOverwrite);
Preserve original data
Experimental input files should generally remain unchanged.
Open input files in READ mode and store
derived quantities and analysis results
in separate output files.
Object ownership and file lifetime
Understanding object ownership is particularly important when working with ROOT files.
ROOT may associate objects with the directory from which they were retrieved or in which they were created.
For example, a histogram retrieved from a file is normally owned by that file's directory.
When the file is closed, the associated histogram may be deleted.
Incorrect usage
TFile file("events.root", "READ");
TH1D* hist = file.Get<TH1D>("h_pt");
file.Close();
hist->Draw(); // Invalid if the histogram was deleted
The pointer may refer to an object that no longer exists.
Such a pointer is called a dangling pointer.
Detaching a histogram from a file
A histogram can be detached from its associated
directory using SetDirectory().
TFile file("events.root", "READ");
if (file.IsZombie())
{
return;
}
TH1D* hist = file.Get<TH1D>("h_pt");
if (!hist)
{
return;
}
hist->SetDirectory(nullptr);
file.Close();
// The histogram remains accessible.
std::cout << hist->GetEntries() << '\n';
delete hist;
Once detached, the histogram must be managed independently.
Object-specific behaviour
Different ROOT classes have different ownership and storage requirements.
For example, a TTree may need continued
access to its source file when reading entries.
Keep the input file open throughout tree-based data processing.
Automatic resource management
C++ objects created on the stack are destroyed automatically when they leave their scope.
void analyse()
{
TFile file("events.root", "READ");
if (file.IsZombie())
{
return;
}
// Perform the analysis.
}
The file is automatically closed when
the TFile object is destroyed.
For dynamically allocated objects, modern C++ smart pointers can be used:
#include <memory>
#include <TFile.h>
void analyse()
{
std::unique_ptr<TFile> file(
TFile::Open("events.root", "READ")
);
if (!file || file->IsZombie())
{
return;
}
// Perform the analysis.
}
This approach follows the C++ resource management principle known as RAII (Resource Acquisition Is Initialisation).
Frequently used TFile methods
| Method | Description |
|---|---|
TFile::Open() |
Open or create a ROOT file |
IsZombie() |
Check whether construction failed |
IsOpen() |
Check whether the file is open |
Get<T>() |
Retrieve an object of a specified type |
GetName() |
Return the file name |
GetSize() |
Return the file size in bytes |
GetListOfKeys() |
Retrieve the directory's keys |
GetDirectory() |
Retrieve a subdirectory |
ls() |
List directory contents |
mkdir() |
Create a directory |
cd() |
Change the current ROOT directory |
WriteObject() |
Write an object into the directory |
Write() |
Write associated in-memory objects |
Close() |
Close the file |
Some of these methods are inherited from ROOT directory-related classes.
For detailed method descriptions, consult the TFile class reference.
Common problems
The ROOT file cannot be opened
Check the file path, permissions and file opening mode.
Use IsZombie() and, where applicable,
check whether the returned pointer is null.
Get() returns a null pointer
Possible causes include:
- Incorrect object name.
- Incorrect directory path.
- Incompatible object type.
- The requested object does not exist.
Inspect the file using ls() or TBrowser.
The original file has been overwritten
Check the file opening mode.
RECREATE replaces an existing file.
Use READ for input datasets and a separate
file for analysis results.
The program crashes after closing the file
An object may have been deleted when its owning file was closed.
Keep the file open while using its objects or manage object ownership appropriately.
Objects are written into the wrong directory
Check the current ROOT directory:
gDirectory->pwd();
Alternatively, use WriteObject() to
specify the destination explicitly.
Exercises
Exercise 1 — File inspection
Open the ROOT file provided with your assignment.
Identify:
- The number of top-level keys.
- The names of the stored objects.
- The classes of the stored objects.
- The available subdirectories.
Compare the output of ls() with the
structure displayed by TBrowser.
Exercise 2 — Object retrieval
Retrieve a histogram from an existing ROOT file.
Print its name, title and number of entries.
Ensure that your program handles missing objects correctly.
Exercise 3 — Persistent storage
Create a ROOT file containing two histograms.
Close the file and start a new ROOT session.
Retrieve both histograms and verify that their contents have been preserved.
Exercise 4 — Key cycles
Create a ROOT file containing a histogram.
Reopen the file using UPDATE, modify the
histogram and write it again under the same name.
Inspect the resulting key cycles.
Compare the different stored versions.
Exercise 5 — Directory organisation
Create a ROOT file with two subdirectories:
UnfilteredFiltered
Store a histogram in each directory.
Retrieve the histograms using their corresponding directory paths.
Exercise 6 — Object lifetime
Retrieve a histogram from a ROOT file.
Investigate how calling SetDirectory(nullptr)
affects its lifetime after closing the file.
Explain the difference between the ownership of the file and the ownership of the histogram.
Chapter summary
- ROOT files provide persistent storage for scientific data and C++ objects.
- The
TFileclass provides access to ROOT files. - File opening modes determine how files are accessed.
- Stored objects can be retrieved using
Get<T>(). - Keys describe stored objects and their cycles.
- Directories provide hierarchical organisation.
- Objects can be written using
Write()orWriteObject(). - Object ownership determines object lifetime.
- Original experimental datasets should be preserved.