【代码备忘】C++ fstream 读写 unicode 文件

欢迎加入我们的QQ群,无论你是否工作,学生,只要有c / vc / c++ 编程经验,就来吧!158427611 

 

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

 

 

namespace fileStream
{

    bool readFile_Unicode( const string &file ,wstring &destWstring)
    {
        destWstring.clear();
        //setlocale(LC_ALL,"Chinese-simplified");//设置中文环境
        locale &loc=locale::global(locale(locale(),"",LC_CTYPE));

        std::ifstream filestream (file.c_str(), std::ios::in|std::ios::binary|std::ios::ate);
        filestream.seekg (0, std::ios::end);
        size_t size = (size_t)filestream.tellg();
        filestream.seekg(0,ios::beg);
        char* buffer = new char[size + 1];
        memset(buffer,0,sizeof(char)*(size + 1));
        filestream.read (buffer, size);
        destWstring = (wchar_t*)buffer;
        destWstring.erase(size/2);//删除末尾可能会出现的乱码 /2 是为了unicode 之后 长度只有一半
        filestream.close();
        delete[] buffer;
        //setlocale(LC_ALL,"C");//还原
        locale::global(loc); 
        return !destWstring.empty();
    }

    bool writeFile_Unicode( const string &file ,const wstring &writeWstring )
    {
        //setlocale(LC_ALL,"Chinese-simplified");//设置中文环境
        locale &loc=locale::global(locale(locale(),"",LC_CTYPE)); 

        std::ofstream filestream(file.c_str(), std::ios::out | std::ios::binary | std::ios::ate);
        filestream.clear();
        static const BYTE unicodeHead[]={0xFF,0xFE}; //unicode文件头文件
        filestream.write((char *)unicodeHead,2);
        filestream.seekp(std::ios::end);
        filestream.write((char *)writeWstring.c_str(),writeWstring.length() * 2);
        filestream.close();

        //setlocale(LC_ALL,"C");//还原
        locale::global(loc); 
        return true;
    }
}

 

 

 

 

欢迎加入我们的QQ群,无论你是否工作,学生,只要有c / vc / c++ 编程经验,就来吧!158427611 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值