Loops and accessing directory

I have to access a directory say “mydir” which has 20 .root files say “file01.root, file02.root, …file20.root”.

Editing this post to make it easier to understand with some of my actual code!

{
  int n=4;
  int m=20;
  int string[n]={62,24,19,57};
  int om[n]={2,23,11,15};
  int file1[m]={01,02,03,04,05,06,07,08,09,10,11,12,13,14,15,16,17,18,19,20};
  
  for (int j=0; j<m; j++)
    {
      {
	char cut [100];
	sprintf (cut, "file_0000000%d.root",file1[j]);
	TFile *_file0 = TFile::Open(cut);
	TH1F *h = new TH1F("h","h",70,60,70);
	 cout << "File #: " << j+1 << endl;
      }
          Another for loop to analyze data (irrelevant) 
  }
}

So this code will let me access from “file_00000001 to file_00000009” but when it hits the 10th file it says it does not exist because it has one too many zeros. This is because in the code I manually placed another zero so that the integer of “1” would really be “01”. Now I see how that will ruin the program past the 9th file. Also using the list makes this script highly specific to the set of data I am working with, if I want to use the script for another set of root files in a directory, this would be useless. So what I need is a function or command that will read any number of files in a directory without specifying its specific name. Does that make sense? If not comment below.

Ive checked out [url]Open files in a directory with a for loop but the solution doesn’t work for me, maybe im doing something wrong there and if so just say try that again, but if you have any other clues that would help.

This script will be written in C++

Thanks in advance.

Hey, thanks for the response.

My code is working fine now that I added sprintf (cut, "file_0000000%02d.root",file1[j]);

BUT, if I were to get a folder with root files named “mystats.root[1-6]” how would I alter my code so that it can just say, input the folder name or path, and it will read the files inside, a loop making the files being read one by one. Is this possible? I feel like with a TDirectory and GetListOfFiles commands you can access the files inside a specific folder, but how can you utilize the files to analyze like I am doing currently with this code?

[quote] I feel like with a TDirectory and GetListOfFiles commands you can access the files inside a specific folder, but how can you utilize the files to analyze like I am doing currently with this code?[/quote]You would then use the file name that pass your filter as argument to TFile::Open.

Cheers,
Philippe.

[url]Open files in a directory with a for loop
[url]How to define and assign values to a string array in .header