5

How can I write Persian text like "خلیج فارس" to a file using a std::wfstream?
I tried following code but it does not work.

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

int main()
{
    std::wfstream f("D:\\test.txt", std::ios::out);
    std::wstring s1(L"خلیج فارس");
    f << s1.c_str();
    f.close();

    return 0;
}

The file is empty after running the program.

Amir
  • 10,600
  • 9
  • 48
  • 75
SaeidMo7
  • 1,214
  • 15
  • 22

2 Answers2

5

You can use a C++11 utf-8 string literal and standard fstream and string:

#include <iostream>
#include <fstream>

int main()
{
    std::fstream f("D:\\test.txt", std::ios::out);
    std::string s1(u8"خلیج فارس");
    f << s1;
    f.close();

    return 0;
}
robsn
  • 734
  • 5
  • 18
3

First of all you can left

f << s1.c_str();

Just use

f << s1;

To write "خلیج فارس" with std::wstream you must specify imbue for persian locale like:

f.imbue(std::locale("fa_IR"));

before you write to file.

Mykola
  • 3,343
  • 6
  • 23
  • 39