Salam,
I know it is to late but for other users I choose to write this comment
Even if you precise 0666 as permission, you should know that there is an another factor that is called " process's file mode creation ", so the question is :

how to change current process file mode creation ?

Answer : use umask(permission) at beginning of your program - and give 0000 as permission