Walkthrough: Saving your work, part 2 (15 minutes)


So now you’ve got a histogram fitted to a complicated function. You can use Save as c1.root, quit ROOT, restart it, then load canvas “c1;1” from the file. You’d get your histogram back with the function superimposed… but it’s not obvious where the function is or how to access it now.

What if you want to save your work in the same file as the histograms you just read in? You can do it, but not by using the ROOT browser. The browser will open .root files in read-only mode. To be able to modify a file, you have to open it with ROOT commands.

Try the following: Quit ROOT (note that you can select Quit ROOT from the Browser menu of the browser or the File menu of the canvas). Start ROOT again, then modify “histogram.root” with the following commands:

[] TFile file1("histogram.root","UPDATE")

It is the “UPDATE” option that will allow you to write new objects to “histogram.root”.

[] hist2->Draw()

For the following two commands, hit the up-arrow key until you see them again.1

[] TF1 func("user","gaus(0)+gaus(3)")
[] func.SetParameters(5.,2.,1.,1.,10.,1.)
[] hist2->Fit("user")

Now you can do what you couldn’t before: save objects into the ROOT file:

[] hist2->Write()
[] func.Write()

Close the file to make sure you save your changes2:

[] file1.Close()

Quit ROOT, start it again, and use the ROOT browser to open “histogram.root”. You’ll see a couple of new objects: “hist2;2” and “user;1”. Double-click on each of them to see what you’ve saved.


You wrote the function with func.Write(), but you saw user;1 in the file. Do you see why? It has to do with the name you give to objects in your programming environment, versus the internal name that you give to ROOT. There’s more about this later in the tutorial. I wanted to point it out so that you were aware that, though they seem closely connected at times, the program environment and the ROOT toolkit are two different entities.

Chapter 11 of the ROOT Users Guide has more information on using ROOT files.


In case you care: ROOT stores your ROOT commands in the file “.root-hist” in your home directory; that’s where it gets the lines you see with the up-arrow key. Similarly, the UNIX shell stores the last 5000 commands you’ve typed in .sh-history in your home directory.


I’ve seen some ROOT documentation that suggests that closing the file is optional, since ROOT usually closes the file for you when you quit the program. However, I’ve also seen many ROOT files made unreadable because they weren’t closed properly. I suggest you always explicitly close any file you open!