最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c - Createappend file and write a string from a dialog item, in UTF8 - Stack Overflow

programmeradmin1浏览0评论

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?

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?

Share Improve this question asked Mar 12 at 19:19 BasjBasj 46.7k110 gold badges459 silver badges808 bronze badges 10
  • 3 Is the input read in UTF8? – isrnick Commented Mar 12 at 19:33
  • 1 Your strftime format produces no characters outside the ASCII range, so your file is a plain ASCII file. – stark Commented Mar 12 at 20:45
  • 2 You are writing binary data to the file. There is no conversion. Every byte you pass is written as-is. If you want your output file to be UTF-8 your source data has to be UTF-8. – IInspectable Commented Mar 12 at 20:45
  • 2 Use GetDlgItemTextW() and convert to UTF-8 with WideCharToMultiByte() or equivalent before writing it to the file. – Remy Lebeau Commented Mar 12 at 20:59
  • 1 Windows doesn't support UTF-8; when you call GetDlgItemTextA the text will be converted from UTF-16 using your system codepage. Instead, use GetDlgItemTextW and convert to UTF-8 explicitly. – Jonathan Potter Commented Mar 12 at 22:09
 |  Show 5 more comments

1 Answer 1

Reset to default 6

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);
发布评论

评论列表(0)

  1. 暂无评论