CreateFile always overrides the specified file

I am trying to log actions performed by a service that I wrote using the Windows API and C language, so I created a log file system.

The problem is that with every call to CreateFile, the file is redefined, rather than just opening it and writing to the end of the file.

Here is the code of my WriteInLogfile function:

 void WriteInLogFile(LPCTSTR log_string) { HANDLE hFile; DWORD dBytesWritten; if ((hFile = CreateFile(LOG_FILE_PATH, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE && (GetLastError() == ERROR_FILE_NOT_FOUND)) { if ((hFile = CreateFile(LOG_FILE_PATH, GENERIC_WRITE, 0, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL)) != INVALID_HANDLE_VALUE) { if (!WriteFile(hFile, log_string, strlen(log_string), &dBytesWritten, NULL)) aff_error("WriteInLogFile"); CloseHandle(hFile); } } else { if (!WriteFile(hFile, log_string, strlen(log_string), &dBytesWritten, NULL)) aff_error("WriteInLogFile"); CloseHandle(hFile); } } 

Does anyone know where this problem comes from?

Thanks;)

+7
source share
4 answers

Even if you open an existing file, you do not indicate what you want to add to it. Therefore, it opens as a shared record, and you end up rewriting the contents. You must pass the FILE_APPEND_DATA flag to the CreateFile method. This is best done using the FILE_GENERIC_WRITE flag, which includes FILE_APPEND_DATA

 if ((hFile = CreateFile(LOG_FILE_PATH, FILE_GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE && (GetLastError() == ERROR_FILE_NOT_FOUND)) { 
+6
source

When you open a file, the pointer will always be at the beginning of the file. To add, you need to explicitly look for the end ( SetFilePointer(hFile, 0, 0, FILE_END); ).

Although this may not cause your actual problem, I would replace your current logic, trying to use CreateFile with OPEN_EXSTING and then CREATE_NEW if the first attempt failed. Instead, just pass the OPEN_ALWAYS flag, which pretty much automates this logic - open an existing file if it exists, and create a new one if it isn't.

+2
source

You need to set the file pointer to the end of the file before writing SetFilePointer . See the MSDN Example.

+1
source

I don't see anything obvious in opening for Append in the CreateFile documentation, but you can use SetFilePointer to search at the end of the file before writing.

+1
source

All Articles