copyFiles.C

Go to the documentation of this file.
00001 // Author: Rene Brun
00002 
00003 #include "TROOT.h"
00004 #include "TKey.h"
00005 #include "TFile.h"
00006 #include "TSystem.h"
00007 #include "TTree.h"
00008 
00009   //Example of script showing how to copy all objects (including directories)
00010   //from a source file.
00011   //For each input file, a new directory is created in the current directory 
00012   //with the name of the source file.
00013   //After execution of:
00014   // root > .x copyFiles.C
00015   //the file result.root will contain 4 subdirectories:
00016   // "tot100.root", "hsimple.root", "hs1.root","hs2.root"
00017       
00018 void CopyDir(TDirectory *source) {
00019    //copy all objects and subdirs of directory source as a subdir of the current directory   
00020    source->ls();
00021    TDirectory *savdir = gDirectory;
00022    TDirectory *adir = savdir->mkdir(source->GetName());
00023    adir->cd();
00024    //loop on all entries of this directory
00025    TKey *key;
00026    TIter nextkey(source->GetListOfKeys());
00027    while ((key = (TKey*)nextkey())) {
00028       const char *classname = key->GetClassName();
00029       TClass *cl = gROOT->GetClass(classname);
00030       if (!cl) continue;
00031       if (cl->InheritsFrom(TDirectory::Class())) {
00032          source->cd(key->GetName());
00033          TDirectory *subdir = gDirectory;
00034          adir->cd();
00035          CopyDir(subdir);
00036          adir->cd();
00037       } else if (cl->InheritsFrom(TTree::Class())) {
00038          TTree *T = (TTree*)source->Get(key->GetName());
00039          adir->cd();
00040          TTree *newT = T->CloneTree(-1,"fast");
00041          newT->Write();
00042       } else {
00043          source->cd();
00044          TObject *obj = key->ReadObj();
00045          adir->cd();
00046          obj->Write();
00047          delete obj;
00048      }
00049   }
00050   adir->SaveSelf(kTRUE);
00051   savdir->cd();
00052 }
00053 void CopyFile(const char *fname) {
00054    //Copy all objects and subdirs of file fname as a subdir of the current directory
00055    TDirectory *target = gDirectory;
00056    TFile *f = TFile::Open(fname);
00057    if (!f || f->IsZombie()) {
00058       printf("Cannot copy file: %s\n",fname);
00059       target->cd();
00060       return;
00061    }
00062    target->cd();
00063    CopyDir(f);
00064    delete f;
00065    target->cd();
00066 }  
00067 void copyFiles() {
00068    //main function copying 4 files as subdirectories of a new file
00069    TFile *f = new TFile("result.root","recreate");
00070    CopyFile("tot100.root");
00071    CopyFile("hsimple.root");
00072    CopyFile("hs1.root");
00073    CopyFile("hs2.root");
00074    f->ls();
00075    delete f;
00076 }

Generated on Tue Jul 5 15:44:48 2011 for ROOT_528-00b_version by  doxygen 1.5.1