场景:
1. 需要写入非ascii文本并且与本地编码无关时,除了utf8,unicode编码是另外一个选择,它的好处是占两个字节,便于统计字符和对字符进行处理,因为有对应的宽字节的函数,如wcslen.
代码1,写入二进制值:
#include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <string.h> int main(int argc, char const *argv[]) { const wchar_t* str = L"a中国人的国家asdfamn12312"; FILE* file = _wfopen(L"E:\\中文.txt",L"w"); char header[]={0xff,0xfe}; fwrite(header,1,sizeof(header),file); printf("%d\n",wcslen(str)*2); fwrite(str,1,wcslen(str)*2,file); //fwprintf(file,L"%S",str);以ANSI模式打开文件,这个函数时用不了的. fclose(file); return 0; }
fwprintf is a wide-character version offprintf; infwprintf,format is a wide-character string. These functions behave identically if the stream is opened in ANSI mode.fprintf does not currently support output into a UNICODE stream.
http://msdn.microsoft.com/en-us/library/xkh07fe2.aspx
如果要使用fwprintf的话,要以unicode模式打开文件.
http://msdn.microsoft.com/en-us/library/yeby3zcb.aspx
代码2,写入unicode字符串:
#include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #define _UNICODE int main(int argc, char const *argv[]) { const wchar_t* str = L"a中国人的国家asdfamn12312"; FILE* file = _wfopen(L"E:\\中文.txt",L"w, ccs=UNICODE"); char header[]={0xff,0xfe}; //fwrite(header,1,sizeof(header),file); printf("%d\n",wcslen(str)*2); //fwrite(str,1,wcslen(str)*2,file); fwprintf(file,L"%s",str); fclose(file); return 0; }