#include#include // Create a new ROOT file and write a TH1F histogram to it. void createFileAndWriteHistogram(){ // Create a histogram TH1F* hist = new TH1F("hist", "Example Histogram", 100, 0, 10); // Fill histogram with data for(int i=0; i<10000; i++){ double x = gRandom->Gaus(5, 2); hist->Fill(x); } // Create a new file and write the histogram to it TFile* file = new TFile("example.root", "RECREATE"); hist->Write(); file->Close(); }
#includeBoth examples use the ROOT library (https://root.cern/). The ROOT TFile class provides various options for writing data to files, including support for compression and random access to data.#include // Update an existing ROOT file with new data. void updateExistingFile(){ // Open an existing file in UPDATE mode TFile* file = new TFile("example.root", "UPDATE"); // Get the existing TTree TTree* tree = (TTree*)file->Get("tree"); // Create a new branch in the TTree double x = 0; TBranch* branch = tree->Branch("x", &x, "x/D"); // Fill the new branch with data for(int i=0; i<10000; i++){ x = gRandom->Gaus(0, 1); tree->Fill(); } // Write the new branch to the file branch->Write(); // Close the file file->Close(); }