Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cannot write the full buffer with WriteFile function

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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 WCHARs 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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading