How to Read Objects from a File ?

There are two ways to read an object from a file.

  • Via TFile::Get or TDirectory::Get if you are in a sub-directory. Assume an existing file f (created by TFile f("myfile.root")). You can list all the keys (persistent objects in the file) via f.ls() or via the browser (see TBrowser). To read an object in memory (example a TShape object), you can do:
  • TShape *shape = (TShape*)f.Get(shape_name);
    

    f.Get will create an object of class TShape with the following sequences of operations:

    • Find the key (eg. shape_name) in the list of keys.
    • Create a TBuffer object.
    • Read the buffer from the file.
    • Create an empty object by calling the default constructor for the referenced class in TKey.
    • Call the Streamer function for this new object.

    In case of an object with multiple cycles, one can return a cycle (a la VMS) with f.Get(name;cycle).

  • Via TKey::Read. The first method via TDirectory::Get is interesting to return an object by its name in complete random access. In case of a very long list of objects to be processed sequentially (this could be a list of events), it is simpler and more efficient to scan the list of keys directly. The example below illustrates at the same time the use of an iterator to loop on all keys of a file.
  •    TIter nextkey(f.GetListOfKeys());
       TKey *key;
       while (key = (TKey*)nextkey()) {
          Event *event = (Event*)key->ReadObj();
          event->Process();
       {

What happens if your job crashes while you write a file?

In case a program does not terminate in a clean way, the file directory is may be not written at the end of the file. Next time you use the file, ROOT will automatically detect this situation and will recover the directory by scanning sequentially the list of keys in the file. If the file has been opened in UPDATE mode, the recovered directory will be automatically written to the file. This automatic recovery procedure is possible because of redundant information written to the file. In case you write large TTrees, you may have large buffers in memory. In case of a job crash, you may loose a lot of data. A mechanism has been foreseen for this case. See TTree::AutoSave.