我已經搜索過要做到這一點,但我無法找到我做錯了什麼。我試圖讓這個函數在每次調用時附加數據,但它總是這樣做一旦。如果該文件不存在,它會創建一個新的和文件編寫一次,如果該文件存在,它什麼都不做(或者覆蓋)如何在win32中追加文件中的數據
void WriteToFile (char data[],wchar_t filename[])
{
HANDLE hFile;
DWORD dwBytesToWrite = (DWORD)strlen(data);
DWORD dwBytesWritten ;
BOOL bErrorFlag = FALSE;
hFile = CreateFile((LPCWSTR)filename, // name of the write
GENERIC_WRITE, // open for writing
0, // do not share
NULL, // default security
CREATE_NEW, // create new file only
FILE_ATTRIBUTE_NORMAL, // normal file
NULL); // no attr. template
if (hFile == INVALID_HANDLE_VALUE)
{
DisplayError(TEXT("CreateFile"));
_tprintf(TEXT("Terminal failure: Unable to open file \"%s\" for write.\n"), filename);
return;
}
bErrorFlag = WriteFile(
hFile, // open file handle
data, // 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)
{
DisplayError(TEXT("WriteFile"));
printf("Terminal failure: Unable to write to file.\n");
}
else
{
if (dwBytesWritten != dwBytesToWrite)
{
// This is an error because a synchronous write that results in
// success (WriteFile returns TRUE) should write all data as
// requested. This would not necessarily be the case for
// asynchronous writes.
printf("Error: dwBytesWritten != dwBytesToWrite\n");
}
else
{
_tprintf(TEXT("Wrote %d bytes to %s successfully.\n"), dwBytesWritten, filename);
}
}
CloseHandle(hFile);
}
而這正是我所說的功能WM_COMMAND
//When a menu item selected execute this code
case IDM_FILE_SAVE:
saveBool = true;
char Str[] = "this is my own data";
wchar_t filename[] = L"data.txt";
WriteToFile(Str, filename);
break;
爲什麼不使用C++標準庫? –
您需要在* dwCreationDisposition *中使用* OPEN_ALWAYS *而不是* CREATE_NEW *。並在* dwDesiredAccess *必須* FILE_APPEND_DATA *,但不* GENERIC_WRITE * – RbMm
@ RBMm謝謝,這很好運行 –