Search code examples
c++stringunicodepersianfarsi

Writing persian ( farsi ) by class wfstream in output file


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.


Solution

  • 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;
    }