C++ fstream 读写 unicode 文件

本文介绍了一种在C++中处理Unicode文件的方法,包括如何读取和写入带有特定Unicode标识的文件。通过使用标准模板库(STL)中的文件流对象,并结合本地编码设置,实现了对Unicode文本的有效操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原文转载于:https://blog.youkuaiyun.com/moooxin/article/details/24620511

所谓的unicode文件,无非就是在文件头部插入了 0xFFFE的标志。。。读写的时候对应的读写 就可以了。


[cpp]  view plain  copy
  1. namespace fileStream  
  2. {  
  3.   
  4.     bool readFile_Unicode( const string &file ,wstring &destWstring)  
  5.     {  
  6.         destWstring.clear();  
  7.         //setlocale(LC_ALL,"Chinese-simplified");//设置中文环境  
  8.         locale &loc=locale::global(locale(locale(),"",LC_CTYPE));  
  9.   
  10.         std::ifstream filestream (file.c_str(), std::ios::in|std::ios::binary|std::ios::ate);  
  11.         filestream.seekg (0, std::ios::end);  
  12.         size_t size = (size_t)filestream.tellg();  
  13.         filestream.seekg(0,ios::beg);  
  14.         char* buffer = new char[size + 1];  
  15.         memset(buffer,0,sizeof(char)*(size + 1));  
  16.         filestream.read (buffer, size);  
  17.         destWstring = (wchar_t*)buffer;  
  18.         destWstring.erase(size/2);//删除末尾可能会出现的乱码 /2 是为了unicode 之后 长度只有一半  
  19.         filestream.close();  
  20.         delete[] buffer;  
  21.         //setlocale(LC_ALL,"C");//还原  
  22.         locale::global(loc);   
  23.         return !destWstring.empty();  
  24.     }  
  25.   
  26.     bool writeFile_Unicode( const string &file ,const wstring &writeWstring )  
  27.     {  
  28.         //setlocale(LC_ALL,"Chinese-simplified");//设置中文环境  
  29.         locale &loc=locale::global(locale(locale(),"",LC_CTYPE));   
  30.   
  31.         std::ofstream filestream(file.c_str(), std::ios::out | std::ios::binary | std::ios::ate);  
  32.         filestream.clear();  
  33.         static const BYTE unicodeHead[]={0xFF,0xFE}; //unicode文件头文件  
  34.         filestream.write((char *)unicodeHead,2);  
  35.         filestream.seekp(std::ios::end);  
  36.         filestream.write((char *)writeWstring.c_str(),writeWstring.length() * 2);  
  37.         filestream.close();  
  38.   
  39.         //setlocale(LC_ALL,"C");//还原  
  40.         locale::global(loc);   
  41.         return true;  
  42.     }  
  43. }  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值