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