C++ 读入文件中的中文字符

环境:C++,VS2013,32位WIN7
转载:https://www.cnblogs.com/poemqiong/p/4609829.html
一、文件类型为Unicode

/// 函数功能: 读入文件内容
/// 参考:http://blog.csdn.net/xiaobai1593/article/details/7060730
///
wstring readFileIntoStringuNNICODE(const char * filename) {
    ifstream ifile(filename, ios::binary);
    wstring res;
    if (ifile) {
        wchar_t wc;
        while (!ifile.eof()) {
            ifile.read((char *)(&wc), 2);
            res = res + wc;
        }
    }
    ifile.close();
    return res;
}

二、文件类型为ANSI

///
/// 函数功能:读入ANSI文件中的中文字符
/// 参考:http://tieba.baidu.com/p/1865939813
///
wstring readFileIntoStringuANSI(const char * filename) {
    wifstream ifile(filename);
    wstring res;
    ifile.imbue(std::locale("CHS"));
    if (ifile) {
        wchar_t wc;
        while (!ifile.eof()) {
            ifile.read((&wc), 1);
            res = res + wc;
        }
    }
    ifile.close();
    return res;
}

CHS为简体中文的意思
w为宽的意思,即wstring是宽的string

char vs. wchar_t
char is supposed to hold a character, usually a 1-byte character.
wchar_t is supposed to hold a wide character, and then, things get
tricky: On Linux, a wchar_t is 4-bytes, while on Windows, it’s 2-bytes

imbue函数为更改区域设置

locale imbue(
   const locale& _Loc
);

C/C++程序中,locale(即系统区域设置,即国家或地区设置)将决定程序所使用的当前语言编码、日期格式、数字格式及其它与区域有关的设置,locale设置的正确与否将影响到程序中字符串处理(wchar_t如何输出、strftime()的格式等)。因此,对于每一个程序,都应该慎重处理locale设置。

C locale和C++ locale是独立的。C locale用setlocale(LC_CTYPE, “”)初始化,
C++ locale用std::locale::global(std::locale(“”))初始化。这样就可以根据当前运行环境正确设置locale。
basic_ios::eof

指示流的结尾是否已到达。

bool eof( ) const;
  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值