in reply to file check loop

You have been given a lot of useful comments on various faulty details in your code, but I was going to suggest the same thing as Cristoforo: I think that you should take a look at the glob function. It is often much more practical in a number of respects than opendir/readdir.