Search code examples
c++writefilewchar

Can WriteFile() be used to write wchar_t characters to a file?


I am trying to write a string of type wchar_t to a file using WriteFile(). Here is the code:

void main()
{
  wchar_t dataString[1024];

  HANDLE hEvent, hFile;
  DWORD dwBytesWritten, dwBytesToWrite;

  hFile = CreateFileW(L"e:\\test.txt", GENERIC_WRITE | GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

  if(hFile == INVALID_HANDLE_VALUE)
  {
     printf("Invalid file handle: %d\n", GetLastError());
     return;
  }

  wcscpy(dataString, L"Hello");
  dwBytesToWrite = wcslen(dataString);
  WriteFile(hFile, (LPVOID )dataString, dwBytesToWrite, &dwBytesWritten, NULL);

  CloseHandle(hFile);

}

I expect the string Hello to be written to the file. However the output inside the file is like this:

H e l

Any idea why it is not writing the entire string Hello to the file?


Solution

  • dwBytesToWrite = wcslen(dataString);
    

    does not return the number of bytes but the number of characters. As you use wide characters (2 bytes per character), only some of them will be written to the file.

    Try this instead:

    dwBytesToWrite = wcslen(dataString) * sizeof(wchar_t);