Search code examples
winapivisual-c++file-iontfsmovefileex

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)?


Solution

  • 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.