如何将文本附加到Windows中的文件?

时间:2013-09-21 13:42:19

标签: c++ c windows winapi

每次调用此函数时,旧文本数据都会丢失?告诉我如何维护以前的数据并附加新数据。

此功能被调用10次:

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

2 个答案:

答案 0 :(得分:8)

在CreateFile函数中,将数据附加到文件的参数是FILE_APPEND_DATA而不是FILE_ALL_ACCESS。 以下是一个示例:http://msdn.microsoft.com/en-us/library/windows/desktop/aa363778(v=vs.85).aspx

答案 1 :(得分:7)

您应该将FILE_APPEND_DATA作为dwDesiredAccess传递给CreateFile,如File Access Rights Constants中所述(请参阅Appending One File to Another File上的示例代码)。虽然这会使用正确的访问权限打开文件,但您的代码仍负责设置file pointer。这是必要的,因为:

  

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

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

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)WriteEvent的参数也应该是常量:

WriteEvent(LPCWSTR pRenderedContent)