【问题标题】:How to open unicode file with ifstream using mingw under Windows?如何在 Windows 下使用 mingw 使用 ifstream 打开 unicode 文件?
【发布时间】:2014-07-18 05:53:59
【问题描述】:

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

我需要使用 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 一起使用的解决方案?非常感谢您。

【问题讨论】:

  • 奇怪的代码。如果WINDOWS 部分仅包含在 Windows 中,那么该文件如何在 Linux 中打开?也就是说,这是真正的代码吗?
  • 我认为this question on StackOverflow about UTF8 encoding wifstream的答案最好回答这个问题。
  • @MrGregs:完全没有必要为了读取 UTF-8 数据而经历如此复杂的过程。问题是对通过cout 显示该数据的结果的错误解释,仅此而已。

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


【解决方案1】:

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

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

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

#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 );
}

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


作为替代方案,您可以使用 Windows API MultiByteToWideChar 编写转换函数。

例如,以下代码与带有-D USE_WINAPI 的g++ 4.8.2 完美配合:

#undef UNICODE
#define UNICODE
#include <windows.h>
#include <shellapi.h>       // ShellAbout

#ifndef USE_WINAPI
#   include <codecvt>          // std::codecvt_utf8_utf16
#   include <locale>           // std::wstring_convert
#endif
#include <fstream>          // std::ifstream
#include <iostream>         // std::cerr, std::endl
#include <stdexcept>        // std::runtime_error, std::exception
#include <stdlib.h>         // EXIT_FAILURE
#include <string>           // std::string, std::wstring

namespace my {
    using std::ifstream;
    using std::ios;
    using std::runtime_error;
    using std::string;
    using std::wstring;

    #ifndef USE_WINAPI
        using std::codecvt_utf8_utf16;
        using std::wstring_convert;
    #endif

    auto hopefully( bool const c ) -> bool { return c; }
    auto fail( string const& s ) -> bool { throw runtime_error( s ); }

    #ifdef USE_WINAPI
        auto wstring_from_utf8( char const* const utf8_string )
            -> wstring
        {
            if( *utf8_string == '\0' )
            {
                return L"";
            }
            wstring result( strlen( utf8_string ), L'#' );  // More than enough.
            int const n_chars = MultiByteToWideChar(
                CP_UTF8,
                0,      // Flags, only alternative is MB_ERR_INVALID_CHARS
                utf8_string,
                -1,     // ==> The string is null-terminated.
                &result[0],
                result.size()
                );
            hopefully( n_chars > 0 )
                || fail( "MultiByteToWideChar" );
            result.resize( n_chars );
            return result;
        }
    #else
        auto wstring_from_utf8( char const* const utf8_string )
            -> wstring
        {
            wstring_convert< codecvt_utf8_utf16< wchar_t > > converter;
            return converter.from_bytes( utf8_string );
        }
    #endif

    auto text_of_file( string const& filename )
        -> string
    {
        ifstream f( filename, ios::in | ios::binary );
        hopefully( !f.fail() )
            || fail( "file open" );
        string result;
        string s;
        while( getline( f, s ) )
        {
            result += s + '\n';
        }
        return result;
    }

    void cpp_main()
    {
        string const    utf8_text   = text_of_file( "spanish.txt" );
        wstring const   wide_text   = wstring_from_utf8( utf8_text.c_str() );
        //ShellAbout( 0, L"Spanish text", wide_text.c_str(), LoadIcon( 0, IDI_INFORMATION ) );
        MessageBox(
            0,
            wide_text.c_str(),
            L"Spanish text",
            MB_ICONINFORMATION | MB_SETFOREGROUND
            );
    }
}  // namespace my

auto main()
    -> int
{
    using namespace std;
    try
    {
        my::cpp_main();
        return EXIT_SUCCESS;
    }
    catch( exception const& x )
    {
        cerr << "!" << x.what() << endl;
    }
    return EXIT_FAILURE;
}

【讨论】:

  • 我使用 Ubuntu,这就是我无法轻松访问 Visual C++ 的原因。我确实尝试使用图形消息框代替 cout,但结果相同。
  • @L.A.Rabida:如果你得到相同的结果,那么你忘了转换为 UTF-16。如果你得到明显相同的结果(gobbledegook),那么也许你确实翻译了但调用了MessageBox 的 ANSI 版本并转换了参数,或者类似的东西。没法说。
  • 我确实不得不稍微更改代码,因为我遇到了一些编译器错误,但在那之后它工作了!极好的!非常感谢!
  • 想一想,可能没有必要将文件读取为二进制文件,而将其读取为二进制文件可能会导致结果中出现不需要的控制字符(回车)。现在它显然正在工作,您可以尝试使用文本模式阅读。当/如果文本模式工作时,它是绝对可取的,以避免必须明确处理 Unix 和 Windows 行尾约定的差异。
猜你喜欢
  • 2010-10-23
  • 2011-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多