转自http://blog.csdn.net/zaffix/article/details/7217701
为实现用C语言写UTF-8编码的文件,测试了以下两种情况。
第一种情况,为fopen指定一个编码,然后写入wchar_t字符串,最终写入的文件就是UTF-8编码的了,原理不清楚,估计是fwrite时对wchar_t做了编码转换(如果写入char的话就会乱码)。
#include<stdio.h>
#include<tchar.h>
intmain()
{
FILE*fp=fopen("test.txt","wt+,ccs=UTF-8");
wchar_t*s=_T("hello,你好!");
fwrite(s,sizeof(wchar_t),wcslen(s),fp);
fclose(fp);
return0;
}
#include <stdio.h>
#include <tchar.h>
int main()
{
FILE* fp = fopen("test.txt", "wt+,ccs=UTF-8");
wchar_t* s = _T("hello, 你好!");
fwrite(s, sizeof(wchar_t), wcslen(s), fp);
fclose(fp);
return 0;
}
第二种情况,先将字符串编码转换为UTF-8格式的,然后再写入。
#include<stdio.h>
#include<string.h>
#include<Windows.h>
intmain()
{
FILE*fp=fopen("test.txt","wb+");
//写入UTF-8的BOM文件头
charheader[3]={(char)0xEF,(char)0xBB,(char)0xBF};
fwrite(header,sizeof(char),3,fp);
char*s="hello,你好!";
wchar_twc[256];
//将ANSI编码的多字节字符串转换成宽字符字符串
intn=MultiByteToWideChar(CP_ACP,0,s,strlen(s),wc,256);
if(n>0)
{
wc[n]=0;
charmb[1024];
//将宽字符字符串转换成UTF-8编码的多字节字符串
n=WideCharToMultiByte(CP_UTF8,0,wc,wcslen(wc),mb,1024,NULL,NULL);
if(n>0)
{
mb[n]=0;
fwrite(mb,sizeof(char),strlen(mb),fp);
}
}
fclose(fp);
return0;
}
转载于:https://blog.51cto.com/oneprog/1315023