用C语言写UTF-8编码的文件

来源:互联网 发布:淘宝网总裁 编辑:程序博客网 时间:2024/04/27 23:50

原文地址:http://blog.csdn.net/zaffix/article/details/7217701

为实现用C语言写UTF-8编码的文件,测试了以下两种情况。

第一种情况,为 fopen 指定一个编码,然后写入 wchar_t 字符串,最终写入的文件就是UTF-8编码的了,原理不清楚,估计是 fwrite 时对 wchar_t 做了编码转换(如果写入 char 的话就会乱码)。

[cpp] view plaincopy
  1. #include <stdio.h>  
  2. #include <tchar.h>  
  3.   
  4. int main()  
  5. {  
  6.     FILE* fp = fopen("test.txt""wt+,ccs=UTF-8");  
  7.   
  8.     wchar_t* s = _T("hello, 你好!");  
  9.   
  10.     fwrite(s, sizeof(wchar_t), wcslen(s), fp);  
  11.   
  12.     fclose(fp);  
  13.   
  14.     return 0;  
  15. }  


第二种情况,先将字符串编码转换为UTF-8格式的,然后再写入。

[cpp] view plaincopy
  1. #include <stdio.h>  
  2. #include <string.h>  
  3. #include <Windows.h>  
  4.   
  5. int main()  
  6. {  
  7.     FILE* fp = fopen("test.txt""wb+");  
  8.   
  9.     // 写入UTF-8的BOM文件头  
  10.     char header[3] = {(char)0xEF, (char)0xBB, (char)0xBF};  
  11.     fwrite(header, sizeof(char), 3, fp);  
  12.   
  13.     char* s = "hello, 你好!";  
  14.     wchar_t wc[256];  
  15.     // 将ANSI编码的多字节字符串转换成宽字符字符串  
  16.     int n = MultiByteToWideChar(CP_ACP, 0, s, strlen(s), wc, 256);  
  17.     if ( n > 0 )  
  18.     {  
  19.         wc[n] = 0;  
  20.   
  21.         char mb[1024];  
  22.         // 将宽字符字符串转换成UTF-8编码的多字节字符串  
  23.         n = WideCharToMultiByte(CP_UTF8, 0, wc, wcslen(wc), mb, 1024, NULL, NULL);  
  24.         if ( n > 0 )  
  25.         {  
  26.             mb[n] = 0;  
  27.             fwrite(mb, sizeof(char), strlen(mb), fp);  
  28.         }  
  29.     }  
  30.   
  31.     fclose(fp);  
  32.   
  33.     return 0;  
  34. }  
0 0
原创粉丝点击