Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CreateFile always override the specified file

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 ;)

like image 823
B F Avatar asked Mar 27 '12 14:03

B F


1 Answers

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))
    {
like image 135
JaredPar Avatar answered Sep 19 '22 01:09

JaredPar