Home | News | Documentation | Download

Open TFile in function

ROOT Version: ROOT 6.18/04

Hi all, I have a macro that I use to compare multiple different files in the same way. To tidy up my code I want to do all of the opening of TFiles in a function like so:

#include "TFile"

void OpenTruthFile(TFile* truthfile, Int_t RunTypeFlag);

void TestMacro(){

Int_t RunTypeFlag = 1;
TFile* truthfile;
OpenTruthFile(truthfile, RunTypeFlag);
}

void OpenTruthFile(TFile* truthfile, Int_t RunTypeFlag){
  if(RunTypeFlag==1){
 truthfile = TFile::Open("Test1.root","read");
}
  else if(RunTypeFlag==2){
 truthfile = TFile::Open("Test2.root","read");
}
}

It gives the error: " no viable overloaded ‘=’".
What’s the correct way to do this?
Thanks

TFile* OpenTruthFile(Int_t RunTypeFlag);

void TestMacro() {
   Int_t RunTypeFlag = 1;
   TFile* truthfile = OpenTruthFile(tRunTypeFlag);
}

TFile *OpenTruthFile(Int_t RunTypeFlag){
   if(RunTypeFlag==1){
     return TFile::Open("Test1.root","read");
   }
   else if(RunTypeFlag==2){
      retrun TFile::Open("Test2.root","read");
   }
   return nullptr;
}

(or keep you existing code pattern and pass the pointer by reference OpenTruthFile(TFile*& truthfile, Int_t RunTypeFlag);

PS. Update to correct the function signature (thanks @bethlong06)

Modifying your response to the following works:

#include "TFile.h"

TFile* OpenTruthFile(Int_t RunTypeFlag);

void OpenFileFunction() {
   Int_t RunTypeFlag = 1;
   TFile* truthfile = OpenTruthFile(RunTypeFlag);
}

TFile* OpenTruthFile(Int_t RunTypeFlag){
   if(RunTypeFlag==1){
     return TFile::Open("/Users/bethlong/Documents/PADME/SignalToyMC/Data.tmp/test/200913TestGeneratedSignalsLandauAmp200k.root","read");
   }
   else if(RunTypeFlag==2){
      return TFile::Open("Test2.root","read");
   }
   return nullptr;
}

Thanks a lot

yes if you create them with new std::ifstream

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.