Unicode字符集下WriteFile中文处理

最近在使用WriteFile函数时发现,vc2008中unicode字符集下处理中文乱码的一些解决方法,归纳如下


1. 写入的时候采用多字节char类型

    HANDLE hFile;
    DWORD nBytes;
    hFile=CreateFile(_T("test.txt"),GENERIC_WRITE,FILE_SHARE_WRITE,NULL,CREATE_ALWAYS,0,NULL);
    char msg[]="我是我的我";
    if(hFile!=INVALID_HANDLE_VALUE)
    {
       WriteFile(hFile,msg, sizeof(msg) ,&nBytes,NULL);
       CloseHandle(hFile);
    }


2. 直接写入unicode的头字节
    HANDLE hFile;
     DWORD nBytes;
     hFile=CreateFile(_T("test.out"),GENERIC_WRITE,FILE_SHARE_WRITE,NULL,CREATE_ALWAYS,0,NULL);
     WCHAR msg[]=L"我是我的我";
     if(hFile!=INVALID_HANDLE_VALUE)
     {
         WORD a=0xFEFF;
         WriteFile(hFile,&a,sizeof(a),&nBytes,NULL);
         WriteFile(hFile,msg, lstrlen(msg) * sizeof(TCHAR),&nBytes,NULL);
         CloseHandle(hFile);
     }


3. 使用wcstombs转换成多字节,需要引用wchar.h和locale.h
  HANDLE hFile;
     DWORD nBytes;
     hFile=CreateFile(_T("test.out"),GENERIC_WRITE,FILE_SHARE_WRITE,NULL,CREATE_ALWAYS,0,NULL);
     WCHAR msg[]=L"我是我的我";
     if(hFile!=INVALID_HANDLE_VALUE)
     {
           char buf[sizeof(msg)];
           setlocale(LC_ALL, ".936");
           wcstombs(buf, msg, sizeof(msg));
           WriteFile(hFile,buf, sizeof(buf),&nBytes,NULL);
           CloseHandle(hFile);
     }
//
hFile=CreateFile(_T("test.txt"),GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_ALWAYS,0,NULL);
if(hFile!=INVALID_HANDLE_VALUE)
{
   WCHAR line[256]={0};
   BOOL bResult;
   bResult=ReadFile(hFile,line,sizeof(line),&nBytes,NULL);
   if(nBytes!=0)
   {
       printf("%s\r\n",line);
   }
   CloseHandle(hFile);
}


4. 使用WideCharToMultiByte转换成多字节

    (省略)


你可能感兴趣的:(Unicode字符集下WriteFile中文处理)