TChain: Adding files by reading filenames in a text file

Dear root experts,

I am trying to use a while loop to read filenames in a text file and then add them to a TChain. However, it seems my code fails to add all the root files to the chain. Here is part of my code:

I use 5 root files to test my code. The number of entries is shown to be 5986010. However, if I simply add files by using the silly code:(sorry could only include one figure in my post)


Then the number of entries is shown to be 6101959!

For the above testing, I was using root 6.14/06. I suppose the silly code should be correct but I could not see what is wrong with the while loop. Thanks for the help.

Please read tips for efficient and successful posting and posting code

ROOT Version: Not Provided
Platform: Not Provided
Compiler: Not Provided

Why don’t you call AddFile with each line as you read it?

That is what I try to do in the first place. I put the addfile into the while loop but only the last file is added and the root files in first 4 lines are said to be doesn’t exist. The same error occurs if I only include 2 lines in the text file. Here is my code.


You should either be able to do data->AddFile(line.c_str()) if TChain copies the string, or you shouldn’t free temp (if it doesn’t). In the later case, there’s no need to declare temp before the loop, just declare it where it’s initialized.

Just before calling AddFile, try printing what you’re adding (i.e. std::cout << "|" << temp << "|\n"; or std::cout << "|" << line.c_str() << "|\n";) to check it’s what you expect (with no extraneous spaces or anything.

Thanks for the advice! I tried your testing and I got something interesting:

The last “|” does not show up except for the last line. I have absolutely no idea what is happening…

I think I know what’s happening. You have a file with Windows (DOS) line endings, which are CR LF. UNIX line endings are LF only. The CR sends the cursor back to the start of the line and the ‘|’ at the end of the line gets printed over the ‘|’ at the start. I expect your last line isn’t followed by a line break, right?

You need to run dos2unix on your input list so you have UNIX line endings.

1 Like

Thanks beojan!!! This is the problem! Everything works after switching to UNIX!