I am trying to use WriteFile
to write a simple text in a .TXT file. Here's my declaration:
// For WriteFile fuction
BOOL writeFile;
LPCVOID textToWrite = L"SakyLabs: Hello, MDE.";
DWORD numberOfBytes = (DWORD)wcslen(textToWrite);
DWORD numberOfBytesWritten;
numberOfBytes
was based on Microsoft's example from here.
Next, the WriteFile function:
writeFile = WriteFile(createFile, textToWrite, numberOfBytes, &numberOfBytesWritten, NULL);
I am getting createFile from a previous CreateFileW
call. Also, I am using Unicode functions.
WriteFile
works, but I only get this part of the text written in the file:
S a k y L a b s : H
What am I doing wrong?
The problem is that you're creating a wide-charecter string L"..."
. Each WCHAR
is two bytes long -- because Windows is using UTF-16 for wide strings. wcslen
counts the number WCHAR
elements in it rather than bytes.
Either multiply the string length by the size of a WCHAR
:
DWORD numberOfBytes = (DWORD)wcslen(textToWrite)*sizeof(WCHAR);
or use narrow char strings (preferably UTF-8 encoded if you actually use non-ASCII):
LPCVOID textToWrite = "SakyLabs: Hello, MDE.";
DWORD numberOfBytes = (DWORD)strlen(textToWrite);