Hello Rooters,
Here is my dilemma:
I have a rootfile with a tree that already exists called “MCA927”, in this tree there are many branches. I then run a root macro to add branches to this tree. But, here is the catch, every time I run my macro it creates these branches over and over again. I want these branches to be written once and if I do run it again, then I would like them to be overwritten. My code is below for reference. Thanks a bunch!!
void MCA927RawViewer(char filename[130], bool ToCal){
TFile *file = new TFile(filename, "update"); //update appends to the rootfile
TTree *t = (TTree*)gDirectory->Get("MCA927");
UInt_t spLength = 0;
Double_t liveTime = 0.0;
Double_t totLiveTime = 0.0;
Double_t realTime = 0.0;
Double_t totRealTime = 0.0;
Int_t runNumber = 0;
Int_t nentries = Int_t(t->GetEntries());
//new branches to add to the tree
TBranch *TotalLiveTime = t->Branch("totLiveTime",&totLiveTime,"totLiveTime/D");
TBranch *TotalRealTime = t->Branch("totRealTime",&totRealTime,"totRealTime/D");
t->SetBranchAddress("spLength",&spLength);
t->GetEntry(0);
const UInt_t kSpLength = spLength;
UInt_t spectrum[kSpLength];
TString histname_1 = filename;
TString histname = "(File: " + histname_1 + "): Raw Counts vs. Bin Number";
TH1F *uncal = new TH1F("uncal", histname , spLength, 0.0, spLength);
t->SetBranchAddress("spectrum", &spectrum);
t->SetBranchAddress("spLength", &spLength);
t->SetBranchAddress("runNumber",&runNumber);
t->SetBranchAddress("liveTime", &liveTime);
t->SetBranchAddress("realTime", &realTime);
//the outer loop loops over the sub runs, the inner loop adds the bin content from each sub-run
for (Int_t j = 0; j < nentries; j++) {
t->GetEntry(j);
totLiveTime += liveTime;
totRealTime += realTime;
for (UInt_t i = 0; i < kSpLength; i++) {
uncal->AddBinContent(i,spectrum[i]);
}
}
TotalLiveTime->Fill();
TotalRealTime->Fill();
uncal->GetYaxis()->SetTitle("Counts");
uncal->GetXaxis()->SetTitle("Bin Number");
uncal->GetXaxis()->CenterTitle();
uncal->GetYaxis()->CenterTitle();
uncal->Write("", TObject::kOverwrite); //overwrite here so we dont keep creating new keys
t->Write("", TObject::kOverwrite);
t->Print();
delete file;
if (ToCal == true) {CalibrateAndSave(filename,kSpLength);}
}//end program