CreateFile always override the specified file

寵の児 提交于 2020-01-14 08:05:10

问题


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


回答1:


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



回答2:


When you open a file, the pointer will always be positioned to the beginning of the file. To append, you need to explicitly seek to the end (SetFilePointer(hFile, 0, 0, FILE_END);).

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




回答3:


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




回答4:


I couldn't see anything obvious about opening for Append in the CreateFile documentation, but you could use the SetFilePointer function to seek to the end of the file before writing.



来源:https://stackoverflow.com/questions/9891794/createfile-always-override-the-specified-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!