场景:
1. 需要写入非ascii文本并且与本地编码无关时,除了utf8,unicode编码是另外一个选择,它的好处是占两个字节,便于统计字符和对字符进行处理,因为有对应的宽字节的函数,如wcslen.
2.需要注意的亮点,要先写入0xff,0xfe文件头,之后使用fwprintf时用%S(大写)格式写入宽字节字符串。
3.使用_wfopen支持中文路径.
代码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 of
fprintf; in fwprintf,
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:
#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;
}
[C/C++标准库]_[读写中文路径的文件--写入unicode字符串],布布扣,bubuko.com
[C/C++标准库]_[读写中文路径的文件--写入unicode字符串]
原文:http://blog.csdn.net/infoworld/article/details/38553869