Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
rfile001_basics.C File Reference

Detailed Description

Demonstrate the basic usage of RFile.

void write_hist_to_rfile(const char *fileName)
{
// Create a histogram to write to the file
TH1D hist("hist", "hist", 10, 0, 100);
hist.FillRandom("gaus", 1000);
// Create a new ROOT file for writing
auto file = ROOT::Experimental::RFile::Recreate(fileName);
// Put objects into the file (in this case we write the same object multiple times
// under different paths). Note that the ownership of `hist` is untouched by `file->Put`.
file->Put(hist.GetName(), hist);
file->Put(std::string("a/") + hist.GetName(), hist);
file->Put(std::string("a/b/") + hist.GetName(), hist);
// When `file` goes out of scope it will write itself to disk.
// To manually write the file to disk without closing it, one can use `file->Flush()`.
}
void read_hist_from_rfile(const char *fileName)
{
// Open an existing ROOT file for reading (will throw an exception if `fileName` cannot be read).
auto file = ROOT::Experimental::RFile::Open(fileName);
// Iterate all keys of all objects in the file (this excludes directories by default - see the documentation of
// ListKeys() for all the options).
for (auto key : file->ListKeys()) {
// Retrieve the objects from the file. `file->Get` will return a `std::unique_ptr` to the object, or `nullptr`
// if the object isn't there.
// Once an object is retrieved, it is fully owned by the application, so it survives even if `file` is closed.
auto hist = file->Get<TH1D>(key.GetPath());
if (!hist)
continue;
std::cout << key.GetClassName() << " at " << key.GetPath() << ';' << key.GetCycle() << ":\n";
std::cout << " entries: " << hist->GetEntries() << "\n";
}
}
void rfile001_basics()
{
const char *const fileName = "rfile_basics.root";
gSystem->Unlink(fileName);
}
ROOT::Detail::TRangeCast< T, true > TRangeDynCast
TRangeDynCast is an adapter class that allows the typed iteration through a TCollection.
R__EXTERN TSystem * gSystem
Definition TSystem.h:582
static std::unique_ptr< RFile > Open(std::string_view path)
Opens the file for reading.
Definition RFile.cxx:205
static std::unique_ptr< RFile > Recreate(std::string_view path, const RRecreateOptions &opts=RRecreateOptions())
Opens the file for reading/writing, overwriting it if it already exists.
Definition RFile.cxx:225
1-D histogram with a double per channel (see TH1 documentation)
Definition TH1.h:926
virtual Double_t GetEntries() const
Return the current number of entries.
Definition TH1.cxx:4457
virtual int Unlink(const char *name)
Unlink, i.e.
Definition TSystem.cxx:1392
TH1D at hist;1:
entries: 1000
TH1D at a/hist;1:
entries: 1000
TH1D at a/b/hist;1:
entries: 1000
Warning
This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback is welcome!
Date
2025-11-06
Author
Giacomo Parolini giaco.nosp@m.mo.p.nosp@m.aroli.nosp@m.ni@c.nosp@m.ern.c.nosp@m.h

Definition in file rfile001_basics.C.