open (not fopen) will allow you to set permissions of the file.
setuid will allow you to set the uid of the process.
So, as an example (from memory not tested)
setuid(501) // assuming www-data is 501
fd = open(filename, O_RDRW | O_CREAT, 0644)