Instead of immediately writing to a file, write to a some designated memory block, or even a memory mapped file, or something that goes to RAM and not the disk. Then when you are finished, then you create the new file and write the memory contents to a file.
Paul is right to state that sprintf is 'a slow library function' and that its use in speed critical code could be problematic. However, the questions that need to be asked are 1) Is the code using sprintf critical in terms of speed? In your case I don't think it is particularly speed critical. 2) What is the general overhead of changing to something else? Paul suggests generating the file names up-front before the while loop is entered. In some situations this would work well, but in your case you don't know before running the program how many file names are needed. Your test file has 51 images, but what if the data was changed to contain 100, 1000, 100,000 images to be extracted? The overhead of the 'house-keeping' code could well exceed the expected speed improvements.
In your case if I was writing this program as a test for a CS course, I would leave the sprintf in the loop but explain in accompying documentation about the speed issue of using sprintf in the loop. Others may take a different view, but that is my humble opinion.