# How to Read Objects from a File?¶

Retrieving objects from a ROOT file can be done with with TFile::GetObject method:

In [1]:
TFile inputFile ("inputFile.root");
TH1F* h = nullptr;
inputFile.GetObject("myHisto",h);


What happens behind the scenes, in a nutshell, is the following:

• The key with name "myHisto"is found in the list of keys.
• A TBuffer object is created.
• The buffer is read from the file.
• An empty object is created by calling the default constructor for the class referenced in TKey.
• Call the Streamer method for this new object.

In case of an object with multiple cycles, one can pick a particular cycle with a name like "myHisto;" (e.g. "myHisto;2")

Another approach could be adopted acting directly of keys, for example when the names of the objects contained in the file are not known a priori or when a long series of objects needs to be read sequentially (the method described above is indeed interesting to pick an object by its name in complete random access). The example below illustrates how to loop over all keys of a file:

In [5]:
for (TObject* keyAsObj : *inputFile.GetListOfKeys()){
auto key = dynamic_cast<TKey*>(keyAsObj);
std::cout << "Key name: " << key->GetName() << " Type: " << key->GetClassName() << std::endl;
}

Key name: myHisto Type: TH1F
Key name: myVector Type: vector<int>


## 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 may not be written at the end of the file. Next time this file is used, ROOT will automatically detect this abnormal termination 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 is foreseen for this case as well. See TTree::AutoSave.

## Can a file being written by a process be read simultaneously by another process?¶

It is thanks to the redundancies mentioned above that the ROOT file format allows to read a file which is being written by a separate process at the same time. This can be particularly important for online applications where a Data Acquisition System may be writing a large ROOT file which is "spied" by a separate monitoring process.