【发布时间】:2017-09-17 15:58:29
【问题描述】:
我已经搜索过这样做,但我找不到我做错了什么。我试图让这个函数在每次调用时都附加数据,但它总是执行一次。如果文件不存在,它会创建一个新文件并只在文件上写入一次,如果文件存在,它什么也不做(或者可能覆盖)
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 谢谢,效果很好
标签: file winapi visual-c++ win32gui