Vc2008中Unicode字符集下WriteFile中文處理
阿新 • • 發佈:2019-02-07
最近在使用WriteFile函式時發現,vc2008中unicode字符集下處理中文亂碼的一些解決方法,歸納如下
1. 寫入的時候採用多位元組char型別
2. 直接寫入unicode的頭位元組
3. 使用WideCharToMultiByte轉換成多位元組
(省略)
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) { DWORD a=0xFEFF; WriteFile(hFile,&a,sizeof(a),&nBytes,NULL); WriteFile(hFile,msg, lstrlen(msg) * sizeof(TCHAR),&nBytes,NULL);//第三個引數可以直接sizeof(msg) CloseHandle(hFile); }
3. 使用WideCharToMultiByte轉換成多位元組
(省略)
4. 使用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); }
摘自:http://blog.sina.com.cn/s/blog_4de7c05f0100inob.html#bsh-73-197000054