Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between OPEN_ALWAYS and CREATE_ALWAYS in CreateFile() of Windows API

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

like image 265
Kristian Spangsege Avatar asked Jan 22 '13 22:01

Kristian Spangsege


People also ask

What does CreateFile do?

The CreateFile function can create a new file or open an existing file. You must specify the file name, creation instructions, and other attributes. When an application creates a new file, the operating system adds it to the specified directory.

What is lpFileName?

[in] lpFileName. The name of the file or device to be created or opened. You may use either forward slashes (/) or backslashes (\) in this name. In the ANSI version of this function, the name is limited to MAX_PATH characters.


1 Answers

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 
like image 167
Jon Avatar answered Sep 18 '22 20:09

Jon