|
| 1 | +// \file tutorials/io/experimental/rfile.py |
| 2 | +// \ingroup Base ROOT7 |
| 3 | +// \author Giacomo Parolini <[email protected]> |
| 4 | +// \date 2025-06-11 |
| 5 | +// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback |
| 6 | +// is welcome! |
| 7 | + |
| 8 | +void write_hist_to_rfile(const char *fileName) |
| 9 | +{ |
| 10 | + // Create a histogram to write to the file |
| 11 | + auto hist = TH1D("hist", "hist", 10, 0, 100); |
| 12 | + hist.FillRandom("gaus", 1000); |
| 13 | + |
| 14 | + // Create a new ROOT file for writing |
| 15 | + auto file = ROOT::Experimental::RFile::Recreate(fileName); |
| 16 | + |
| 17 | + // Put objects into the file (in this case we write the same object multiple times |
| 18 | + // under different paths). Note that the ownership of `hist` is untouched by `file->Put`. |
| 19 | + file->Put(hist.GetName(), hist); |
| 20 | + file->Put(std::string("a/") + hist.GetName(), hist); |
| 21 | + file->Put(std::string("a/b/") + hist.GetName(), hist); |
| 22 | + |
| 23 | + // When `file` goes out of scope it will write itself to disk. |
| 24 | + // To manually write the file to disk without closing it, one can use `file->Flush()`. |
| 25 | +} |
| 26 | + |
| 27 | +void read_hist_from_rfile(const char *fileName) |
| 28 | +{ |
| 29 | + // Open an existing ROOT file for reading (will throw an exception if `fileName` cannot be read). |
| 30 | + auto file = ROOT::Experimental::RFile::Open(fileName); |
| 31 | + // Iterate all keys of all objects in the file (this excludes directories by default - see the documentation of |
| 32 | + // ListKeys() for all the options). |
| 33 | + for (auto key : file->ListKeys()) { |
| 34 | + // Retrieve the objects from the file. `file->Get` will return a `std::unique_ptr` to the object, or `nullptr` |
| 35 | + // if the object isn't there. |
| 36 | + // Once an object is retrieved, it is fully owned by the application, so it survives even if `file` is closed. |
| 37 | + auto hist = file->Get<TH1D>(key.GetPath()); |
| 38 | + std::cout << key.GetClassName() << " at " << key.GetPath() << ';' << key.GetCycle() << ":\n"; |
| 39 | + std::cout << " entries: " << hist->GetEntries() << "\n"; |
| 40 | + } |
| 41 | +} |
| 42 | + |
| 43 | +void rfile001_basics() |
| 44 | +{ |
| 45 | + const char *const fileName = "rfile_basics.root"; |
| 46 | + |
| 47 | + write_hist_to_rfile(fileName); |
| 48 | + read_hist_from_rfile(fileName); |
| 49 | + |
| 50 | + gSystem->Unlink(fileName); |
| 51 | +} |
0 commit comments