Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the ReplaceFile Windows API a convenience function only?

Is the ReplaceFile Windows API a convenience function only, or does it achieve anything beyond what could be coded using multiple calls to MoveFileEx?

I'm currently in the situation where I need to

  1. write a temporary file and then
  2. rename this temporary file to the original filename, possibly replacing the original file.

I thought about using MoveFileEx with MOVEFILE_REPLACE_EXISTING (since I don't need a backup or anything) but there is also the ReplaceFile API and since it is mentioned under Alternatives to TxF.

This got me thinking: Does ReplaceFile actually do anything special, or is it just a convenience wrapper for MoveFile(Ex)?

like image 357
Martin Ba Avatar asked Jul 12 '13 08:07

Martin Ba


2 Answers

I think the key to this can be found in this line from the documentation (my emphasis):

The replacement file assumes the name of the replaced file and its identity.

When you use MoveFileEx, the replacement file has a different identity. Its creation date is not preserved, the creator is not preserved, any ACLs are not preserved and so on. Using ReplaceFile allows you to make it look as though you opened the file, and modified its contents.

The documentation says it like this:

Another advantage is that ReplaceFile not only copies the new file data, but also preserves the following attributes of the original file:

  • Creation time
  • Short file name
  • Object identifier
  • DACLs
  • Security resource attributes
  • Encryption
  • Compression
  • Named streams not already in the replacement file

For example, if the replacement file is encrypted, but the replaced file is not encrypted, the resulting file is not encrypted.

like image 160
David Heffernan Avatar answered Sep 28 '22 06:09

David Heffernan


Any app that wants to update a file by writing to a temp and doing the rename/rename/delete dance (handling all the various failure scenarios correctly), would have to change each time a new non-data attribute was added to the system. Rather than forcing all apps to change, they put in an API that is supposed to do this for you.

So you could "just do it yourself", but why? Do you correctly cover all the failure scenarios? Yes, MS may have a bug, but why try to invent the wheel?

NB, I have a number of issues with the programming model (better to do a "CreateUsingTemplate") but it's better than nothing.

like image 34
MJZ Avatar answered Sep 28 '22 05:09

MJZ