Some general hints to prevent anyone from having the same problems:
Always use the three-args version of open. Even for just reading a file. And always specify the mode (yes, even for reading!).
Always try to use system(LIST) or exec(LIST) and not system(EXPR) or exec(EXPR). You really don't want to need to quote things yourself.
Running code under -T (taint) can be useful aswell... (since it forces you to do something with the input before you can use it (in system, in open, ...)).