cwinapiutf-8printf

Create/append file and write a string from a dialog item, in UTF8


I'm getting text from a dialog item and from a date with:

char input[65536];
char date[11];
GetDlgItemText(hDlg, IDC_INPUTEDIT, input, sizeof(input));
strftime(date, 11, "%Y-%m-%d", tm_info);

Then I write it to file with:

f = fopen("test.txt", "ab");  // same with "a"
fprintf(f, "%s %s\n", date, input);

Problem: the output file is in Windows 1252 and not UTF8. How to get this into UTF8 instead?


Solution

  • If you don't manifest your app for UTF-8 then GetDlgItemText() (which maps to GetDlgItemTextA() in your case) will output text in the user's locale.

    Use GetDlgItemTextW() instead to get the text as UTF-16 and then convert it to UTF-8 using WideCharToMultiByte() (or equivalent) before writing it to the file, eg:

    WCHAR input[65536];
    char converted[ARRAY_SIZE(input)*4];
    char date[11];
    GetDlgItemTextW(hDlg, IDC_INPUTEDIT, input, ARRAY_SIZE(input));
    WideCharToMultiByte(CP_UTF8, 0, input, -1, converted, ARRAY_SIZE(converted), NULL, NULL);
    strftime(date, 11, "%Y-%m-%d", tm_info);
    ...
    f = fopen("test.txt", "ab");
    fprintf(f, "%s %s\n", date, converted);