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

2022-07-28,,,

环境: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;

本文地址:https://blog.csdn.net/qq_45045793/article/details/109632833

《C++ 读入文件中的中文字符.doc》

下载本文的Word格式文档,以方便收藏与打印。