I searched MSDN about
HANDLE WINAPI CreateFile(
_In_ LPCTSTR lpFileName,
_In_ DWORD dwDesiredAccess,
_In_ DWORD dwShareMode,
_In_opt_ LPSECURITY_ATTRIBUTES lpSecurityAttributes,
_In_ DWORD dwCreationDisposition,
_In_ DWORD dwFlagsAndAttributes,
_In_opt_ HANDLE hTemplateFile
);
and if dwCreationDisposition == CREATE_ALWAYS or OPEN_ALWAYS, it says
Creates a new file, always. 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. For more information, see the Remarks section of this topic.
and
Opens a file, always. If the specified file exists, the function succeeds and the last-error code is set to ERROR_ALREADY_EXISTS (183). If the specified file does not exist and is a valid path to a writable location, the function creates a file and the last-error code is set to zero.
So I'm not sure that if the function failed, would GetLastError() be ERROR_ALREADY_EXISTS ?
Please give me an example if so.
Thanks a lot.
Fast answer: No.
According to what's specified:
ERROR_ALREADY_EXISTSshall be returned byGetLastError()right after aCreateFile()call only when the file exists,dwCreationDispositionis set toCREATE_ALWAYSorOPEN_ALWAYSand theCreateFile()succeeds.If
CreateFile()fails withCREATE_ALWAYSorOPEN_ALWAYSset asdwCreationDisposition, thenGetLastError()shall return the appropriate last-error code indicating the reason why the file could not be opened, but that cannot beERROR_ALREADY_EXISTSas the user specifically requested to open or create the file, regardless if it exists or not.This shall not be confused with the return value of
GetLastError()when a call toCreateFile()withdwCreationDispositionset toCREATE_NEWfails because the file exists. In this case,GetLastError()shall returnERROR_FILE_EXISTSand neverERROR_ALREADY_EXISTS.