Hint: Create a file with a temporary filename in the correct location, write the file's content and attributes and if everything went well rename it into the correct filename. If something fails delete the file.
Of course you can create the tempfile somewhere else, but then the copy operation may fail (not enough diskspace? insufficent permissions?) which could leave you with an incomplete/invalid file. Reducing the 'critical' operation to a rename drastically reduces the chances of something going wrong.