如何在Windows下使用mingw打开ifstream的unicode文件?

时间:2014-05-28 20:29:09

标签: c++ windows unicode utf-8 mingw

请注意,这与How to open an std::fstream (ofstream or ifstream) with a unicode filename?不同。这个问题是关于unicode 文件名,这个是关于unicode文件内容

我需要使用ifstream打开UTF-8 unicode文件(包含西班牙语字符)。在Linux下这没有问题,但在Windows下它是。

bool OpenSpanishFile(string filename)
{
    ifstream spanishFile;
    #ifdef WINDOWS
    spanishFile.open(filename.c_str(),ios::binary);
    #endif

    if (!spanishFile.is_open()) return false;
    spanishFile.clear();
    spanishFile.seekg(ios::beg);
    while (spanishFile.tellg()!=-1)
    {
        string line="";
        getline(spanishFile,line);
        //do stuff
        cout << line << endl;
    }
    return true;

}

我在Linux下编译它:

i586-mingw32msvc-g++ -s -fno-rtti test.cpp test.exe

然后在wineconsole test.exe中运行。

输出包含各种奇怪的字符,因此它尝试将unicode文件打开为不同的东西。

我在互联网上搜索了很多关于如何以这种方式打开unicode文件,但我无法让它工作。

有没有人知道与mingw一起使用的解决方案?非常感谢你。

1 个答案:

答案 0 :(得分:1)

最有可能(目前还不清楚所呈现的代码是否是真实的代码)你看到垃圾的原因是Windows中的std::cout默认在非UTF-8控制台窗口中显示其结果。

要正确检查您是否正确读取UTF-8文件,只需收集字符串中的所有输入,将其从UTF-8转换为UTF-16 wstring,然后使用{{1 (或直接控制台输出)。

以下UTF-8→UTF-16转换功能与Visual C ++ 12.0很好地配合使用:

MessageBoxW

不幸的是,尽管它只使用标准的C ++ 11功能,但它无法使用MinGW g ++ 4.8.2编译,但希望你有Visual C ++(毕竟它是免费的)。


作为替代方案,您可以使用Windows API #include <codecvt> // std::codecvt_utf8_utf16 #include <locale> // std::wstring_convert #include <string> // std::wstring auto wstring_from_utf8( char const* const utf8_string ) -> std::wstring { std::wstring_convert< std::codecvt_utf8_utf16< wchar_t > > converter; return converter.from_bytes( utf8_string ); } 编译转换函数。

例如,以下代码适用于带有MultiByteToWideChar的g ++ 4.8.2:

-D USE_WINAPI

enter image description here