CreateFile / WriteFile does not destroy the contents of the old file

Old content is not destroyed. Instead, data is written, so I still see the old content. What didn’t I do?

hFile = CreateFile(fname, // open testfile.txt GENERIC_WRITE, // open for reading 0, // do not share NULL, // default security OPEN_ALWAYS, // FILE_ATTRIBUTE_NORMAL, // normal file NULL); // no attribute template dwBytesToWrite = buff.GetLength(); WriteFile(hFile, buff.GetBuffer(100), dwBytesToWrite, &dwBytesWritten, NULL); 
+4
source share
3 answers

You specified an invalid value for dwCreationDisposition . You need to specify CREATE_ALWAYS .

Creates a new file always. If the specified file exists and is writable, the function overwrites the file, the function succeeds, and the last error code is 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 code for the last error is set to zero.

+5
source

In dwCreationDisposition you need to specify CREATE_ALWAYS.

+1
source

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.

+1
source

Source: https://habr.com/ru/post/1389830/


All Articles