Not really sure, but is perror outputting to stdout or stderr ? it may be related, because I think the printf is to stdout, and perror is to stderr... I am not sure how to change the order, but I think there would be a way. If you want you can redirect one or the other by redirecting 1> /path/stdout.txt 2> /path/stderr.txt
more info, and how to redirect both can be found here:
http://www.cpqlinux.com/redirect.html
hope this helps