re: Saving histograms in a file AFTER book+fill

Mark Pollack (markp@bnl.gov)
Tue, 14 Jul 1998 22:52:38 -0400


Dear Roottalk,

I am running into some difficulty trying to
book/fill histograms inside a *directory structure*
and save them to a file AFTER the mkdirs/books/fills.

Following the advice from this previous thread, I can
easily save histograms which are not inside any directories.
However, if I make some directories and put histograms
inside them, the statement

gROOT->GetList()->Write()

does not write out the directories and the histos contained inside
of them.

Here is an example macro. I tried to save the directories
explicitly at the end put I feel I did not make a "correct" root
file since

.ls and myfile->ls() show different results...

{

gROOT->Reset();

gROOT->cd();
TH1F *hpx = new TH1F("hpx","This is the px distribution",100,-4,4);

gROOT->mkdir("1DS");
gROOT->cd("1DS");
TH1F *hpy = new TH1F("hpy","This is the py distribution",100,-4,4);

gROOT->cd();
gROOT->mkdir("2DS");
gROOT->cd("2DS");
TH2F *hpxpy = new TH2F("hpxpy","py ps px",40,-4,4,40,-4,4);

gROOT->cd("1DS");
for (int i=1; i<100; i++) {
hpx->Fill(i,i);
}

gROOT->cd("2DS");
for (int i=1; i<100; i++) {
hpxpy->Fill(i,i,i);
}

TDirectory *fdir;
TDirectory *mdir;
TFile *hfile = new TFile("file.root","RECREATE");
if (hfile->IsOpen()) {
hfile->pwd(); //file.root
gROOT->pwd(); //Rint:

//gROOT->GetList()->Write(); //does not work on directories


TList *l = gROOT->GetList();
TIter next(l);
l->ls();
TObject *obj;
while((obj = (TObject*) next())) {
if (obj->IsA() == TDirectory::Class()) {
mdir = (TDirectory*)obj;
hfile->cd();
fdir = hfile->mkdir(mdir->GetName());
fdir->cd();
if (fdir->IsWritable()) {
printf("directory contents..");
mdir->GetList()->Print();
mdir->GetList()->Write();
fdir->Write();
}
} else {
obj->Write();
}
}
}

root [0] .x rootdirs.cc
file.root:/
Rint:/
OBJ: TH1F hpx This is the px distribution : 0
TDirectory* 1DS 1DS
OBJ: TH1F hpy This is the py distribution : 0
TDirectory* 2DS 2DS
OBJ: TH2F hpxpy py ps px : 0
directory contents..TH1.Print Name= hpy, Total sum= 0
directory contents..TH1.Print Name= hpxpy, Total sum= 6
root [1] .q

root [0] TFile tf = new TFile("file.root");
root [1] .ls
TFile** file.root
TFile* file.root
KEY: TH1F hpx;1 This is the px distribution
KEY: TDirectory 1DS;1 1DS
KEY: TDirectory 2DS;1 2DS
root [2] tf->ls();
TFile** file.root
TFile* file.root
root [3] tf->cd();
root [4] tf->ls();
TFile** file.root
TFile* file.root
root [5] tf->ls("1DS");
TFile** file.root
TFile* file.root
root [6] tf->cd("1DS");

*** Break *** segmentation violation

This is different behavior than in the provided dirs.C sample

root [0] TFile *top = new TFile("top.root");
root [1] .ls
TFile** top.root
TFile* top.root
KEY: TDirectory tof;1 tof
root [2] top->ls();
TFile** top.root
TFile* top.root
KEY: TDirectory tof;1 tof

Any ideas how to easily save the whole thing to a file after the
creating the directory structure + book/filling?

Thanks,
Mark