1

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?

Deep
  • 5,772
  • 2
  • 26
  • 36
Neena
  • 13
  • 1
  • 5

2 Answers2

2
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);
DAXaholic
  • 33,312
  • 6
  • 76
  • 74
0
  1. add Byte order mark (see: https://en.wikipedia.org/wiki/Byte_order_mark)(UTF-8(0xEF,0xBB,0xBF)) at the begining of text file
  2. convert the string to UTF-8 encoding(https://en.wikipedia.org/wiki/UTF-8).

try following

/////////////        
{
unsigned char utf8BOM[3]={0xef,0xbb,0xbf};
unsigned int i=0;
DWORD bytesWrote;
unsigned int stringLen=wcslen(dataString);
WriteFile(hFile,utf8BOM,3,&bytesWrote,0);
unsigned int i=0;
while(i< stringLen){

    unsigned char buf3[3];
    if(((unsigned short)dataString[i])>0x7FF){
        buf3[0]=(0xe0 | (0x0F & (dataString[i]>>12)));
        buf3[1]=(0x80 | (0x03F & (dataString[i]>>6)));
        buf3[2]=(0x80 | (0x03F & (dataString[i])));
        WriteFile(hFile,buf3,3,&bytesWrote,0);
    }
    else{
        if(((unsigned short)dataString[i]) > 0x7F){
            buf3[0]=((dataString[i]>>6)&0x03) | 0xC0;
            buf3[1]=(dataString[i] & 0x3F) | 0x80;
            WriteFile(hFile,buf3,2,&bytesWrote,0);
        }
        else{
            buf3[0]=dataString[i];
            WriteFile(hFile,buf3,1,&bytesWrote,0);
        }
    }

    i++;
}
}
////////////////////
help-info.de
  • 6,695
  • 16
  • 39
  • 41