Ich habe gesucht, um dies zu tun, aber ich kann nicht finden, was ich falsch mache. Ich versuche, diese Funktion hängt Daten jedes Mal, wenn es heißt, aber es immer tun Einmal. Wenn die Datei nicht existiert es ein neues erstellt und für nur einmal auf Datei schreiben, wenn die Datei existiert es tut nichts (oder vielleicht überschreiben)Wie man Daten an eine Datei in Win32 anfügt
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);
}
Und das ist, wo ich die Funktion in 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;
Warum die c nicht verwenden ++ Standard-Bibliothek? –
brauchen Sie * OPEN_ALWAYS * in * dwCreationDisposition * statt * CREATE_NEW *. und in * dwDesiredAccess * muss * FILE_APPEND_DATA * sein, aber nicht * GENERIC_WRITE * – RbMm
@RbMm Danke, das funktioniert gut –