Reading and writing multiple root files

Hi all,
I need to read several root files, process them and write the changes to new root files (if there are 3 input root files, there should be 3 output root files).

Here is a part of my macro that’s doing this job quit well.

std::vector<std::string> root_File_Names = {"user.ktariq.MC16a_merged.root", "user.ktariq.MC16d_merged.root","user.ktariq.MC16e_merged.root"};
TFile* s[3];
TTree* t1[3];

//loop for files
for (Int_t i = 0; i <3; i++){

 s[i] = TFile::Open(root_File_Names[i].c_str());
 t1[i] = (TTree*)s[i]->Get("Efficiencies_1j1b/MuonProbes");
 TH1F *h1 = (TH1F*)s[i]->Get("MCLumiHist");


 Int_t nentries = (Int_t)t1[i]->GetEntries();
 for (Int_t j =0; j <nentries; j++) {
 t1[i]->GetEntry(j);
 }
 cout<<nentries<<endl;

TFile *f= new TFile(Form("ttbar_%d.root",i),"recreate");
h1->Write();

f->Write();
f->Close();
f->Delete();
}

Now, if there are lager numbers of root files, then its better to read root files from a list.txt
trying to read form list

std::ifstream root_File_Names;
 root_File_Names.open("list.txt");

but fails to open files

 error: type 'std::ifstream' (aka 'basic_ifstream<char>') does not provide a subscript operator
   s[i] = TFile::Open(root_File_Names[i].c_str());

Any help regarding this will be appreciated.
Thanks
Regards Khuram Tariq

Try something like this:

   std::ifstream root_File_Names;
   root_File_Names.open("list.txt");
   std::string filename;
   // Read the input list of files and add them to the chain
   while (root_File_Names.good()) {
      root_File_Names >> filename;
      TFile *f = TFile::Open(filename.c_str(),"READ");
      [...]
   }
1 Like

thanks @bellenot, it works, Its a good idea to use While Loop.
but for writing the root files

//withen while_loop
TFile *fwrite= new TFile("out.root","recreate"); 
h1->Write();
fwrite->Close();
fwrite->Delete();

create only one root file. And

//withen while_loop
TFile *fwrite= new TFile(filename.c_str(),"recreate"); 
h1->Write();
fwrite->Close();
fwrite->Delete();

overwrite input root files.

I needs to write new root files for each input root files(with new name or with some suffix to input root files name).
Thanks

Something like this?

//withen while_loop
std::string out_filename = "out_";
out_filename.append(filename);
TFile *fwrite= new TFile(out_filename.c_str(),"recreate"); 
h1->Write();
fwrite->Close();
fwrite->Delete();
1 Like

yup…that’s works. thanks a lot :slight_smile:

1 Like

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