I'm trying to log the actions made by a service I wrote using the Windows-API & C-language, so I made a log file system.
The problem is that at each CreateFile call, the file is overridden instead of just opening it and write at the end of the file.
Here's 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);
}
}
Do someone know where the issue comes from ?
Thanks ;)
Even though you're opening the existing file you're not specifying that you want to append to it. Hence it opens as a generic write and you end up overwriting the contents. You need to pass the FILE_APPEND_DATA
flag to the CreateFile
method. This is best done by 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))
{
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With