Fail to retrieve histogram from file

Good afternoon everyone!

I have a very naive question regarding retrieving a histogram from ROOT file.

I create a root file, generate the histogram, writing it to file and then trying to read it back to plot. The
file is generated, I can access the histogram inside, but I can not plot it. However, if i’m using exactly
the same commands in the terminal, the histogram magically appears. What am I doing wrong?

Please find below the relevant code.

string fileName = "demo.root";
string histoName = "genericHistoName";

void createFile(){

    std::unique_ptr<TFile> myFile(TFile::Open(fileName.c_str(), "recreate"));

}

void writeHisto(){

    unique_ptr<TFile> myFile(TFile::Open(fileName.c_str(), "update"));
    if(!myFile || myFile->IsZombie()) cout << "HOUSTON WE HAVE A PROBLEM" << endl;

    TH1D *h = new TH1D(histoName.c_str(), histoName.c_str(), 100, -4, 4);
    h->FillRandom("gaus",20000);

    myFile->WriteObject(h, h->GetName());
    delete h;

}

void readHisto(){

    std::unique_ptr<TFile> myFile(TFile::Open(fileName.c_str(), "read"));
    if(!myFile || myFile->IsZombie()) cout << "HOUSTON WE HAVE A PROBLEM" << endl;

    TH1D *h = myFile->Get<TH1D>(histoName.c_str());
    if(!h || h->IsZombie()) cout << "HOUSTON WE HAVE ANOTHER PROBLEM" << endl;
    h->Draw();

}

int main(){

    createFile();
    writeHisto();
    readHisto();

    return 0;

}

ROOT Version: 6.22/06
Platform: Ubuntu 18.04

Many thanks in advance!

In readHisto:

    // ...
    h->SetDirectory(0);
    h->Draw();
    // ...

And if you create a standalone application:

void readHisto()
{
    std::unique_ptr<TFile> myFile(TFile::Open(fileName.c_str(), "read"));
    if(!myFile || myFile->IsZombie()) std::cout << "HOUSTON WE HAVE A PROBLEM" << std::endl;

    TH1D *h = myFile->Get<TH1D>(histoName.c_str());
    if(!h || h->IsZombie()) std::cout << "HOUSTON WE HAVE ANOTHER PROBLEM" << std::endl;
    h->SetDirectory(nullptr); // << --- to detach the histogram from the file
    h->Draw();
}

int main(int argc, char *argv[])
{
    TApplication theApp("App",&argc,argv);
    createFile();
    writeHisto();
    readHisto();
    theApp.Run();
    return 0;
}

Thank you both for such quick replies! Your suggestions indeed fix my problem :slight_smile:

1 Like