29

Can anyone explain what the difference is between the creation dispositions OPEN_ALWAYS and CREATE_ALWAYS of the CreateFile() function of the windows API?

To me it seems that they both simply 'create the file if it does not already exist'.

Kristian Spangsege
  • 2,903
  • 1
  • 20
  • 43

1 Answers1

80

CREATE_ALWAYS also truncates the contents if the file already exists. On the other hand, OPEN_ALWAYS will not clobber an already existing file.

Here's how the different values work in tabular form:

                         |                    When the file...
This argument:           |             Exists            Does not exist
-------------------------+------------------------------------------------------
CREATE_ALWAYS            |            Truncates             Creates
CREATE_NEW         +-----------+        Fails               Creates
OPEN_ALWAYS     ===| does this |===>    Opens               Creates
OPEN_EXISTING      +-----------+        Opens                Fails
TRUNCATE_EXISTING        |            Truncates              Fails
Jon
  • 428,835
  • 81
  • 738
  • 806
  • 2
    That was exactly what I was hoping - funny that the documentation is so vaguely formulated. Thanks. – Kristian Spangsege Jan 22 '13 at 23:02
  • 7
    Nice table. Some random thoughts: if the file exists there are 3 outcomes: _Truncates, Fails, Opens_; if the file does not exist there are 2 outcomes: _Creates, Fails_. So 3*2 = 6 different behaviours. Since the _Fails/Fails_ is totally useless, only 5 possibilities remains, and here they are! – rodrigo Jan 22 '13 at 23:10
  • 1
    Also what is important to add to that table is what happens to the [file pointer](https://msdn.microsoft.com/en-us/library/windows/desktop/aa365542(v=vs.85).aspx) when existing file is opened (when `OPEN_ALWAYS` or `OPEN_EXISTING` is specified.) In both cases the file pointer will point to the beginning of the file. So, if you then start writing into that file, it will overwrite the beginning of the file and **will not** append it to the end of file. To change that use `SetFilePointerEx` function with `FILE_END` flag before writing. – ahmd0 Jul 22 '17 at 21:37
  • 1
    @ahmd0 Where `WriteFile`s ends up actually depends on the access mask, if you only ask for file-append it will write to the end of the file on NT. – Anders Sep 04 '19 at 18:33