代码之家  ›  专栏  ›  技术社区  ›  Khaled Alshaya

为什么C++中的宽文件流在默认情况下会缩小写入数据?

  •  18
  • Khaled Alshaya  · 技术社区  · 16 年前

    老实说,我只是在C++标准库中没有得到下面的设计决定。将宽字符写入文件时, wofstream 转换 wchar_t 进入之内 char 字符:

    #include <fstream>
    #include <string>
    
    int main()
    {
        using namespace std;
    
        wstring someString = L"Hello StackOverflow!";
        wofstream file(L"Test.txt");
    
        file << someString; // the output file will consist of ASCII characters!
    }
    

    我知道这与标准有关 codecvt . 有 编解码器 对于 utf8 在里面 Boost .此外,还有一个 编解码器 对于 utf16 通过 Martin York here on SO . 问题是 为什么? 这个 standard codecvt 转换宽字符?为什么不按原样写角色呢?

    还有,我们会变成现实吗? unicode streams 用C++ 0x还是AM在这里漏掉了什么?

    5 回复  |  直到 11 年前
        1
  •  7
  •   AProgrammer    16 年前

    #include <locale>
    #include <fstream>
    #include <ostream>
    #include <iostream>
    
    int main()
    {
        wchar_t c = 0x00FF;
        std::locale::global(std::locale(""));
        std::wofstream os("test.dat");
        os << c << std::endl;
        if (!os) {
            std::cout << "Output failed\n";
        }
    }
    

    $ env LC_ALL=C ./a.out
    Output failed
    

    $ env LC_ALL=en_US.utf8 ./a.out
    $ od -t x1 test.dat
    0000000 c3 bf 0a
    0000003
    

        2
  •  13
  •   Éric Malenfant    16 年前

    wchar_t char

    codecvt<char16_t, char, mbstate_t> codecvt <char32_t, char, mbstate_t> codecvt<wchar_t,char,mbstate_t>

    codecvt_utf8

    codecvt_utf16

    codecvt_utf8_utf16

        3
  •  3
  •   sellibitze    16 年前
        4
  •  2
  •   Leandro T. C. Melo    16 年前

        5
  •  2
  •   mzzzzb    11 年前

    Class basic_filebuf

    wofstream file(L"Test.txt", ios_base::binary); //binary is important to set!  
    wchar_t buffer[128];  
    file.rdbuf()->pubsetbuf(buffer, 128);  
    file.put(0xFEFF); //this is the BOM flag, UTF16 needs this, but mirosoft's UNICODE doesn't, so you can skip this line, if any.  
    file << someString; // the output file will consist of unicode characters! without the call to pubsetbuf, the out file will be ANSI (current regional settings)