c++ wofstream issue in unicode program

1.1k views Asked by At

Using unicode compile in vs2008 How do you output many language characters to a file in C++ with wofstream?

I can do it in C code no problem e.g.

 FILE *out;
 if( (out  = _wfopen( L"test.txt", L"wb" )) != NULL )
 {
     fwprintf(out,L"test\r\n");
     fwprintf(out,L"наказание\r\n");
     fwprintf(out,L"ウェブ全体から検索\r\n");
 }

when I open the file it's all correct, but with below C++ program all I get is the first line and I have tried locale::global(locale("")); with same result.

 wofstream MyOutputStream(L"test.txt"); 
 if(!MyOutputStream)
 {
    AfxMessageBox(L"Error opening file");
    return;
 }

    MyOutputStream << L"test\r\n";
    MyOutputStream << L"наказание\r\n";
    MyOutputStream << L"ウェブ全体から検索\r\n";

    MyOutputStream.close();

and I have tried inserting this with same result:-

  std::locale mylocale(""); 
  MyOutputStream.imbue(mylocale);
2

There are 2 answers

4
user3725395 On

worked it out... here it is:-

    wofstream MyOutputStream(L"c:\\test2.txt", ios_base::binary);

    wchar_t buffer1[128];  
    MyOutputStream.rdbuf()->pubsetbuf(buffer1, 128); 
    MyOutputStream.put(0xFEFF);
    MyOutputStream << L"test\r\n";
    MyOutputStream << L"наказание\r\n";
    MyOutputStream << L"ウェブ全体から検索\r\n";
1
user3725395 On

the final code that works is:-

  wofstream MyOutputStream(L"c:\\test2.txt", ios_base::binary); 
  if(!MyOutputStream)
  {
    AfxMessageBox(L"Error opening file");
    return;
  }
    wchar_t buffer1[128];  
    MyOutputStream.rdbuf()->pubsetbuf(buffer1, 128); 

    MyOutputStream << L"test\r\n";
    MyOutputStream << L"наказание\r\n";
    MyOutputStream << L"ウェブ全体から検索\r\n";

    MyOutputStream.close();