5

Everytime this function is called the old text data is lost?? Tell me how to maintain previous data and appending new data.

This function is called 10 times:

void WriteEvent(LPWSTR pRenderedContent)
{
    HANDLE hFile; 
    DWORD dwBytesToWrite = ((DWORD)wcslen(pRenderedContent)*2);
    DWORD dwBytesWritten = 0;
    BOOL bErrorFlag = FALSE;

    printf("\n");

    hFile = CreateFile(L"D:\\EventsLog.txt", FILE_ALL_ACCESS, 0, NULL, OPEN_ALWAYS,   FILE_ATTRIBUTE_NORMAL, NULL);                 

    if (hFile == INVALID_HANDLE_VALUE) 
    { 
        printf("Terminal failure: Unable to open file \"EventsLog.txt\" for write.\n");
        return;
    }

    printf("Writing %d bytes to EventsLog.txt.\n", dwBytesToWrite);

    bErrorFlag = WriteFile( 
                    hFile,                // open file handle
                    pRenderedContent,      // start of data to write
                    dwBytesToWrite,  // number of bytes to write
                    &dwBytesWritten, // number of bytes that were written
                    NULL);            // no overlapped structure

    if (FALSE == bErrorFlag)
    {
        printf("Terminal failure: Unable to write to file.\n");
    }
    else
    {
        if (dwBytesWritten != dwBytesToWrite)
        {
            printf("Error: dwBytesWritten != dwBytesToWrite\n");
        }
        else
        {
            printf("Wrote %d bytes to EventsLog.txt successfully.\n",dwBytesWritten);
        }
    }

    CloseHandle(hFile);
}
4

2 回答 2

9

您应该传递to ,如FILE_APPEND_DATA文件访问权限常量中所述(请参阅将一个文件附加到另一个文件中的示例代码)。虽然这会使用正确的访问权限打开文件,但您的代码仍然负责设置文件指针。这是必要的,因为:dwDesiredAccessCreateFile

每次打开文件时,系统都会将文件指针放在文件的开头,即偏移量为零。

打开文件后,可以使用SetFilePointerAPI 设置文件指针:

hFile = CreateFile( L"D:\\EventsLog.txt", FILE_APPEND_DATA, 0x0, nullptr,
                    OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr );
if ( hFile == INVALID_HANDLE_VALUE ) {
    printf( "Terminal failure: Unable to open file \"EventsLog.txt\" for write.\n" );
    return;
}

// Set the file pointer to the end-of-file:
DWORD dwMoved = ::SetFilePointer( hFile, 0l, nullptr, FILE_END );
if ( dwMoved == INVALID_SET_FILE_POINTER ) {
    printf( "Terminal failure: Unable to set file pointer to end-of-file.\n" );
    return;
}

printf("Writing %d bytes to EventsLog.txt.\n", dwBytesToWrite);

bErrorFlag = WriteFile( // ...


与您的问题无关,dwBytesToWrite不应使用幻数的计算。而不是* 2你应该写* sizeof(*pRenderedContent). to 的参数也WriteEvent应该是常量:

WriteEvent(LPCWSTR pRenderedContent)
于 2013-09-21T14:16:48.677 回答
9

The parameter for appending data to a file is FILE_APPEND_DATA instead of FILE_ALL_ACCESS in the CreateFile function. Here is an example: http://msdn.microsoft.com/en-us/library/windows/desktop/aa363778(v=vs.85).aspx

于 2013-09-21T13:44:58.777 回答