Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
rfile003_ttree.C
Go to the documentation of this file.
1/// \file
2/// \ingroup ROOT7 tutorial_io
3/// Demonstrate how to read a TTree with RFile.
4///
5/// Note that, due to how TTree handles lifetime and its relationship with TDirectory, writing TTree through RFile
6/// is currently unsupported.
7///
8/// \macro_code
9/// \macro_output
10///
11/// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback
12/// is welcome!
13///
14/// \date 2026-10-12
15/// \author Giacomo Parolini <giacomo.parolini@cern.ch>
16#include <iostream>
17#include <TSystem.h>
18#include <TTree.h>
19#include <ROOT/RDataFrame.hxx>
20#include <ROOT/RFile.hxx>
21
22void read_tree_from_rfile(const char *fileName)
23{
24 // Open an existing ROOT file for reading (will throw an exception if `fileName` cannot be read).
25 // IMPORTANT! This file must remain open while reading data from the tree.
26 auto file = ROOT::Experimental::RFile::Open(fileName);
27
28 // Get back the TTree from the file
29 auto tree = file->Get<TTree>("tree");
30 R__ASSERT(tree); // we just wrote the tree so we expect to find it in the file
31 int intVal;
32 tree->SetBranchAddress("intBranch", &intVal);
33
34 for (auto i = 0; i < tree->GetEntries(); ++i) {
35 tree->GetEntry(i);
36 std::cout << "value[" << i << "] = " << intVal << "\n";
37 }
38}
39
40void rfile003_ttree()
41{
42 const char *const fileName = "rfile_ttree.root";
43
44 // Note that TTree cannot be written to RFile, so we use RDataFrame to write it instead.
45 ROOT::RDataFrame(10).Define("intBranch", "static_cast<int>(rdfentry_)").Snapshot("tree", fileName);
46
47 read_tree_from_rfile(fileName);
48
49 gSystem->Unlink(fileName);
50}
#define R__ASSERT(e)
Checks condition e and reports a fatal error if it's false.
Definition TError.h:139
R__EXTERN TSystem * gSystem
Definition TSystem.h:582
static std::unique_ptr< RFile > Open(std::string_view path, const ROpenOptions &opts=ROpenOptions())
Opens the file for reading.
Definition RFile.cxx:204
RResultPtr< RInterface< RLoopManager > > Snapshot(std::string_view treename, std::string_view filename, const ColumnNames_t &columnList, const RSnapshotOptions &options=RSnapshotOptions())
RInterface< Proxied > Define(std::string_view name, F expression, const ColumnNames_t &columns={})
Define a new column.
ROOT's RDataFrame offers a modern, high-level interface for analysis of data stored in TTree ,...
virtual int Unlink(const char *name)
Unlink, i.e.
Definition TSystem.cxx:1403
A TTree represents a columnar dataset.
Definition TTree.h:95