You need dwCreationDisposition = TRUNCATE_EXISTING . This however:
Opens a file and truncates it so that its size is zero bytes only if it exists. If the specified file does not exist, the function does not work and the last error code is set to ERROR_FILE_NOT_FOUND (2). the calling process must open a file with the GENERIC_WRITE bit set as part of the dwDesiredAccess parameter.
So I will first try to open it with TRUNCATE_EXISTING . If it does not work with ERROR_FILE_NOT_FOUND , then open it with CREATE_NEW .
hFile = CreateFile(fname, GENERIC_WRITE, 0, NULL, TRUNCATE_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if ((hFile == NULL) && (GetLastError() == ERROR_FILE_NOT_FOUND)) { hFile = CreateFile(fname, GENERIC_WRITE, 0, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL); }
EDIT: This is not the best way to do this. CREATE_ALWAYS is the dwCreationDisposition that you want to use. See David Heffernan's answer.
source share