Why does wide file-stream in C++ narrow written data by default?

前端 未结 5 1331
别跟我提以往
别跟我提以往 2020-11-30 05:44

Honestly, I just don\'t get the following design decision in C++ Standard library. When writing wide characters to a file, the wofstream converts wchar_t<

5条回答
  •  长情又很酷
    2020-11-30 06:30

    Check this out: Class basic_filebuf

    You can alter the default behavior by setting a wide char buffer, using pubsetbuf. Once you did that, the output will be wchar_t and not char.

    In other words for your example you will have:

    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)  
    

提交回复
热议问题