Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
rfile001_basics.C
Go to the documentation of this file.
1/// \file
2/// \ingroup ROOT7 tutorial_io
3/// Demonstrate the basic usage of RFile.
4///
5/// \macro_code
6/// \macro_output
7///
8/// \date 2025-11-06
9/// \author Giacomo Parolini <giacomo.parolini@cern.ch>
10
11void write_hist_to_rfile(const char *fileName)
12{
13 // Create a histogram to write to the file
14 TH1D hist("hist", "hist", 10, 0, 100);
15 hist.FillRandom("gaus", 1000);
16
17 // Create a new ROOT file for writing
18 auto file = ROOT::RFile::Recreate(fileName);
19
20 // Put objects into the file (in this case we write the same object multiple times
21 // under different paths). Note that the ownership of `hist` is untouched by `file->Put`.
22 file->Put(hist.GetName(), hist);
23 file->Put(std::string("a/") + hist.GetName(), hist);
24 file->Put(std::string("a/b/") + hist.GetName(), hist);
25
26 // When `file` goes out of scope it will write itself to disk.
27 // To manually write the file to disk without closing it, one can use `file->Flush()`.
28}
29
30void read_hist_from_rfile(const char *fileName)
31{
32 // Open an existing ROOT file for reading (will throw an exception if `fileName` cannot be read).
33 auto file = ROOT::RFile::Open(fileName);
34 // Iterate all keys of all objects in the file (this excludes directories by default - see the documentation of
35 // ListKeys() for all the options).
36 for (auto key : file->ListKeys()) {
37 // Retrieve the objects from the file. `file->Get` will return a `std::unique_ptr` to the object, or `nullptr`
38 // if the object isn't there.
39 // Once an object is retrieved, it is fully owned by the application, so it survives even if `file` is closed.
40 auto hist = file->Get<TH1D>(key.GetPath());
41 if (!hist)
42 continue;
43 std::cout << key.GetClassName() << " at " << key.GetPath() << ';' << key.GetCycle() << ":\n";
44 std::cout << " entries: " << hist->GetEntries() << "\n";
45 }
46}
47
48void rfile001_basics()
49{
50 const char *const fileName = "rfile_basics.root";
51
52 write_hist_to_rfile(fileName);
53 read_hist_from_rfile(fileName);
54
55 gSystem->Unlink(fileName);
56}
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
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:226
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:4574
virtual int Unlink(const char *name)
Unlink, i.e.
Definition TSystem.cxx:1403