每次调用此函数时,旧文本数据都会丢失??告诉我如何维护以前的数据和附加新数据。
这个函数被调用了 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);
}
最佳答案
您应该将 FILE_APPEND_DATA
作为 dwDesiredAccess
传递给 CreateFile
,如 File Access Rights Constants 下所述(参见 Appending One File to Another File 处的示例代码)。虽然这会使用正确的访问权限打开文件,但您的代码仍负责设置 file pointer .这是必要的,因为:
Each time a file is opened, the system places the file pointer at the beginning of the file, which is offset zero.
可以使用 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
的计算不应使用魔数(Magic Number)。您可能应该编写 * sizeof(*pRenderedContent)
而不是 * 2
。 WriteEvent
的参数也应该是常量:
WriteEvent(LPCWSTR pRenderedContent)
关于c++ - 如何将文本附加到 Windows 中的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18933283/