将Unicode UTF-8文件读入wstring [英] Read Unicode UTF-8 file into wstring
问题描述
如何在Windows平台上将Unicode(UTF-8)文件读入 wstring
(s)?
How can I read a Unicode (UTF-8) file into wstring
(s) on the Windows platform?
推荐答案
根据@Hans Passant的评论,最简单的方法是使用 _ wfopen_s 。使用模式 rt,ccs = UTF-8
打开文件。
According to a comment by @Hans Passant, the simplest way is to use _wfopen_s. Open the file with mode rt, ccs=UTF-8
.
这是另一个纯C ++解决方案,最少使用VC ++ 2010:
Here is another pure C++ solution that works at least with VC++ 2010:
#include <locale>
#include <codecvt>
#include <string>
#include <fstream>
#include <cstdlib>
int main() {
const std::locale empty_locale = std::locale::empty();
typedef std::codecvt_utf8<wchar_t> converter_type;
const converter_type* converter = new converter_type;
const std::locale utf8_locale = std::locale(empty_locale, converter);
std::wifstream stream(L"test.txt");
stream.imbue(utf8_locale);
std::wstring line;
std::getline(stream, line);
std::system("pause");
}
除了 locale :: empty code>(这里
locale :: global()
也可以工作)和 wchar_t *
basic_ifstream
构造函数,这甚至应该是非常符合标准(其中标准意味着C ++ 0x,当然)。
Except for locale::empty()
(here locale::global()
might work as well) and the wchar_t*
overload of the basic_ifstream
constructor, this should even be pretty standard-compliant (where "standard" means C++0x, of course).
这篇关于将Unicode UTF-8文件读入wstring的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!