Wfstream does not write

I have the following code snippet in C ++:

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main(){
    wstring ws1 = L"Infinity: \u2210";
    wstring ws2 = L"Euro: €";

    wchar_t w[] = L"Sterling Pound: £";

    wfstream out("/tmp/unicode.txt");
    out.write(ws1.c_str(), ws1.size());
    out << ws1 << endl << ws2 << endl << w << endl;
    out.flush();
    out.close();
}

The program compiles without problems, but the file never opens, and is not written. Moreover, if I use std::wcout, I still don’t get the correct conclusion, just ?for the symbols of infinity and pound.

My g ++ 4.4.3 system works with ubuntu linux 10.4 64 bit.

+3
source share
2 answers

Always set the locale first ... do locale::global( locale( "" ) );. Prior to this, you are in simple C mode, which knows nothing about UTF-8.

In Darwin, this is broken, so I need to do it setlocale( LC_ALL, "" );, but then your program works for me.

Edit

, . wfstream openmode . wofstream , , . . :

wofstream out("/tmp/unicode.txt");

wfstream out("/tmp/unicode.txt", ios::in | ios::out | ios::trunc );
+1

, , , , . C std in/out std:: cin/std:: cout.

setlocale("");  // Loads the local that the machine is configured for (see you config)
                // If it is not configured it default to the "C" locale

, .

std::locale   defaultLocale(""); // from machine config
std::wfstream out;
out.imbue(defaultLocale);        // imbue must be done before opening
                                 // otherwise it is ignored.

out.open("/tmp/unicode.txt");

, , :

if (!out)
{
    std::cout << "Failed to open file\n";
}

:

out.write(ws1.c_str(), ws1.size()); // size() is the number of characters (wide)
                                    // write is expecting the number of bytes.

:

out.flush();    // flush() happens automatically when the file is closed
out.close();    // close() happens automatically when the stream is destroyed.
                // So technically it is better not to use these
                // as they are specific to file streams which will prevent you from
                // easily replacing this with a generic stream
+3
source

Source: https://habr.com/ru/post/1767912/


All Articles