tempfile = mkstemp(filename-XXXX)
write(tempfile)
fsync(tempfile)
close(tempfile)
rename(tempfile, filename)
sync()
Assume the entire write failed if any of the above return an error.
In some systems (nfs and ext3 come to mind), you can skip the fsync and/or sync, but don’t do that. It doesn’t make things significantly faster on the systems where it’s safe, but it definitely will lose data on other systems.
The only loophole I know of is that the final sync can fail, then return anyway. If that happens, the file system is probably hosed anyway.