UTF8文件读写

来源:互联网 发布:用波士顿矩阵分析海尔 编辑:程序博客网 时间:2024/06/04 08:13

2009-04-07 12:00:56|  分类: 默认分类|举报|字号 订阅

最近使用VS2005开发一个小工具操纵UTF-8文本文件,发现VS2005对UTF-8的支持还真差。
仔细阅读了VS2005MSDN,结合查的资料,经过n次碰壁,解决如下。
附: 我有了VS2005MSDN就将MSDN2003删掉了,后来才知道损失有多大,Windows API全部从新版的MSDN删除,还有很多其他有趣的话题。可怜偌大一个因特网,竟然找不到地方下载MSDN2003,郁闷至极,只好下载了一个 Windows server 2003 platform sdk R2终于找到了帮助。
基本方法:
使用VS2005提供的功能读UTF-8文本文件,并将内容转存在以UNICODE存储的内存空间;如果需要写出则使用二进制方式打开文件,使用Windows API函数WideCharToMultiByte转换好后再输出内容到输出文件中。

读文件:
打开文件
 FILE *fp;
 fopen_s(&fp, "file.txt", "rt, ccs=UNICODE");
或者
 fopen_s(&fp, "file.txt", "rt, ccs=UTF-8");
都可以

 wchar_t line[BUFF_SIZE];
 wchar_t str = fgetws(line, BUFF_SIZE, fp);
 if (str == NULL)
 {
  //错误处理
 }

写文件
打开文件
 FILE *fp;
 fopen_s(&fp, "fileout.txt", "w+b");
写UTF-8文件头(必须在后续写之前)
 char line[3]; // UTF-8 file header
 line[0] = 0xef;
 line[1] = 0xbb;
 line[2] = 0xbf;
 fwrite(line, sizeof(char), 3, fp);
写一行
 void WriteUTF8TextLine(FILE *f, CString str) // inline function
 // file must be opened in binary mode
 // Write Unicode String str to UTF-8 file stream as a text line
 {
  char line[BUFF_SIZE];
  str=str+L"\r\n";
  wchar_t *p;
  int len = WideCharToMultiByte(CP_UTF8, 0, p=str.GetBuffer(), str.GetLength(), line, BUFF_SIZE, NULL, NULL);
  if (len==0)
   AfxMessageBox(_T("Error Converting Unicode to UTF-8"));
  else
   fwrite(line, sizeof(char), len, f);
  str.ReleaseBuffer();
 }
 
其他方法:
  1. 使用ICU Library(
http://icu.sourceforge.net/);
  • 使用Glib:ustring(http://www.gtkmm.org/gtkmm2/docs/tutorial/html/ch03s04.html);
  • 使用utfcpp(http://sourceforge.net/projects/utfcpp)开源包开发。
0 0
原创粉丝点击