discodowney
discodowney

Reputation: 1507

CreateFile function with CREATE_ALWAYS Disposition

I use CreateFile to initially create a file, with:

HANDLE hFile = CreateFile (TEXT(fileName.str().c_str()),      
                  GENERIC_WRITE,          
                  0,                     
                  NULL,                   
                  OPEN_ALWAYS,            
                  FILE_ATTRIBUTE_NORMAL,  
                  NULL);             

If I use CreateFile again to try and create the same file again, should it not be an error?

hFile = CreateFile (TEXT(fileName.str().c_str()),      
                  GENERIC_WRITE,          
                  0,                      
                  NULL,                   
                  CREATE_ALWAYS,             
                  FILE_ATTRIBUTE_NORMAL,  
                  NULL);              

I would have thought because I use CREATE_ALWAYS that it fails if the file is already created.

Upvotes: 1

Views: 1677

Answers (3)

Paskas
Paskas

Reputation: 2848

No according to MSDN flag CREATE_ALWAYS means:

If the specified file exists and is writable, the function overwrites the file, the function succeeds, and last-error code is set to ERROR_ALREADY_EXISTS (183). If the specified file does not exist and is a valid path, a new file is created, the function succeeds, and the last-error code is set to zero.

So Function DOESN'T fail when files already exist, it succeeded, just last error is set to ERROR_ALREADY_EXISTS.

Upvotes: 0

acraig5075
acraig5075

Reputation: 10756

CREATE_ALWAYS will do just that, always create it. CREATE_NEW will fail if it's already there.

Upvotes: 0

Andriy
Andriy

Reputation: 8604

No, CREATE_ALWAYS flag makes CreateFile to overwrite the file if it already exists. You should use CREATE_NEW to achieve what you want.

Upvotes: 1

Related Questions