How can I read a Unicode (UTF-8) file into wstring
(s) on the Windows platform?
According to a comment by @Hans Passant, the simplest way is to use _wfopen_s. Open the file with mode rt, ccs=UTF-8
.
Here is another pure C++ solution that works at least with VC++ 2010:
#include
#include
#include
#include
#include
int main() {
const std::locale empty_locale = std::locale::empty();
typedef std::codecvt_utf8 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");
}
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).