Search code examples
c++wchar-t

Write wchar_t* to file - works only for some characters


I have methods which returns unicode texts and i need to write them into file but some characters are not written. I have the following:

const wchar_t* getStandardText() {
    return L"test";
}

const wchar_t* getUnicodeText()
{
    return L"testíček";
}

int main()
{
    FILE *file = fopen(FILE_NAME, "a");

    fputws(getStandardText(), file);
    fputws(getUnicodeText(), file);

    fclose(file);
}

Output in file:

testtestí

Much more confusing for me is that some characters like "í" works and others like "č" not.

  • I am on Windows with VS 2015 Pro.
  • For reading of file i use Notepad++ which tells me the file has ANSI encoding.

Solution

  • This works on Windows... Change your mode parameter to have an explicit encoding...

    FILE *file = fopen("foobar.txt", "a+, ccs=UTF-16LE");
    

    OR

    FILE *file = fopen("foobar.txt", "a+, ccs=UTF-8");
    

    That appears to force the byte-order-marks (FF FE) onto the file header to indicate the file's text is Unicode.