I would make two stabs at this, First 40k Files in one dir on a cd is kinda bad, it will take forever to stat the dir. You may try soting your files into a tree (this kinda reminds me of the old news servers that tried to store all of the groups in one dir, they all moved to a fs tree or db of some sort pretty quickly) For example if your filenames look like this:
B12C113.jpg
D92C113.jpg
G12C934.jpg
B12C117.jpg
You may be able to sort them into a dir tree like this:
\B\1\2C113.jpg
\B\1\2C117.jpg
\D\9\2C113.jpg
\G\1\2C934.jpg
It really depends what your file name convention is. You really just want to split the file names up in a way where you get a clean spread across a lot of dirs where you do not have to stat 40k files when you stat the dir. the task of creating this layout should be very simple with
substr. Let me know if you need more info I may have some code around that shows an example of how to do this.
Then deal with the transfer -- you may notice that it is simplified.
-Waswas