CFile的Unicode宽字符写文件

来源:互联网 发布:淘宝电商平台技术架构 编辑:程序博客网 时间:2024/04/26 23:32

CFileUnicode宽字符写文件

ANSI字符集称为窄字符8位,C语言用unsigned char表示,不能存放世界上所有语言所有文字。

UNICODE字符集称为宽字符16位,C语言用unsigned short表示,可以存放世界上所有语言所有文字。

宽字符字符串表示为一个wchar_t[]数组并由wchar_t* 指针指向它。可以通过用字母L作为字符的前缀将任何ASCII字符表示为宽字符形式。例如,L'/0' 是终止宽(16位)NULL字符。同样,可以通过用字母L作为ASCII字符串的前缀 (L"Hello")   将任何ASCII字符串表示为宽字符字符串形式

ANSI的文件的CFile读写代码一般如下

CFile ansifile

CString str=_T(Hello!);

ansifile.Open(“文件名”,CFile::modeCreate|CFile::modeReadWrite);

ansifile.Write(str,str.Getlength());

ansifile.Close();

上面代码虽然使用宏_T()来申明了CString对象,但是在文件写入的时候,str.Getlength()的值任然位窄字符的长度;如果采用str.Getlength()*sizeofwchar_t)的话,写入文件的将会出现乱码。因此CFile如果要写入宽字符的话,应该采用以下方式:

CFile unicodefile

Wchar_t *str=LHello!;

unicodefile.Open(“文件名”,CFile::modeCreate|CFile::modeReadWrite);

unicodefile.Write(str,wcslen(str)));

unicodefile.Close();

 

CString wchar_t*之间的转换:

1. CString wchar_t*

CString str = "Hell Kesuer";

wchar_t *wstr=path.AllocSysString();

或者:

wchar_t wstr [256];

MultiByteToWideChar(CP_ACP,0,str,-1,wcstring,256);

或者:

USES_CONVERSION;

wchar_t* wstr=A2W(str);

2. wchar_t*CString

wchar_t wcstring[256];

CString str ;;

WideCharToMultiByte(CP_ACP,0,wcstring,256,str.GetBuffer(0),256,NULL,NULL);

str.ReleaseBuffer(0);

 

MultiByteToWideChar

函数功能:该函数映射一个字符串到一个宽字符(unicode)的字符串。由该函数映射的字符串没必要是多字节字符组。

函数原型:int MultiByteToWideChar(UINT CodePage, DWORD dwFlags, LPCSTR lpMultiByteStr, int cchMultiByte, LPWSTR lpWideCharStr, int cchWideChar);

WideCharToMultiByte

函数功能:该函数映射一个unicode字符串到一个多字节字符串。

函数原型:int WideCharToMultiByte(UINT CodePage, DWORD dwFlags, LPWSTR lpWideCharStr, int cchWideChar, LPCSTR lpMultiByteStr, int cchMultiByte, LPCSTR lpDefaultChar, PBOOL pfUsedDefaultChar );

原创粉丝点击