可以使用WriteFile()将wchar_t字符写入文件吗?

时间:2016-05-31 05:53:35

标签: writefile wchar

我正在尝试使用ObservableCollection<MyClass>$(document).on('change','.dataConversionType',function(e) { // Paste Your Code }); OR $(document).on('change','#dataConversionType',function(e) { // Paste Your Code }); 类型的字符串写入文件。这是代码:

wchar_t

我希望将字符串WriteFile()写入文件。但是文件中的输出是这样的:

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);

}

知道为什么不将整个字符串Hello写入文件?

2 个答案:

答案 0 :(得分:0)

dwBytesToWrite = wcslen(dataString);

不返回字节数,而是返回字符数。当您使用宽字符(每个字符2个字节)时,只会将其中一些字符写入该文件。

请改为尝试:

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

答案 1 :(得分:0)

  1. 添加字节顺序标记(请参阅文本文件开头的https://en.wikipedia.org/wiki/Byte_order_mark)(UTF-8(0xEF,0xBB,0xBF))
  2. 将字符串转换为UTF-8 编码(https://en.wikipedia.org/wiki/UTF-8)。
  3. 尝试以下

    /////////////        
    {
    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++;
    }
    }
    ////////////////////