3

Here is my simple C/C++ program:

int main() {
  FILE* f = fopen("MyTest.log", "w");

  fprintf(f, "%ls\n", L"abc");
  fprintf(f, "%ls\n", L"您好"); // Data from a different locale
  fprintf(f, "%ls\n", L"def");
  fclose(f);

  return 0;
}

When I run this program, the generated file does not contain the middle line at all. It appears fprintf simply returns back once it detects a different character set in the passed parameter.

I have tested this program on Windows as well as Ubuntu. The same problem at both the places.

Browsing the forum, I found a few hints such as using _setmode() and fwprintf. However, if possible, I would like to stick to fprintf(). Also, my code needs to work on Windows as well as Linux.

Does anyone know to achieve this? Regards.

Peter
  • 11,260
  • 14
  • 78
  • 155
  • Having non-ASCII characters in the source code is not portable and different compilers handle this differently. – n. m. could be an AI Aug 05 '15 at 05:12
  • For Windows compilers, your source file **must have BOM**. No such requirement in Linux. – n. m. could be an AI Aug 05 '15 at 05:15
  • What encoding should the target file use? – Matteo Italia Aug 05 '15 at 05:21
  • Fo Linux, the default locale normally has UTF-8 encoding. For your program to work on Linux, you only need to add `setlocale(LC_ALL, "")` in the beginning. Microsoft compilers are not UTF-8 friendly, you will need to jump through hoops with them. If you compile on Windows with GCC, it will work just as well as on Linux. – n. m. could be an AI Aug 05 '15 at 05:31
  • In addition to n.m's comment, you don't need that to do with wide character strings. `%s` and `"ÖÜ"` without `L` should do just fine. – Jens Gustedt Aug 05 '15 at 06:49
  • setLocale(LC_ALL, "") works only on Linux. On Windows, it has no effect. – Peter Aug 05 '15 at 19:40
  • The example uses hard-coded strings. In reality, the data is coming from some other source. – Peter Aug 05 '15 at 19:41

1 Answers1

0

I think you need to set locale first to get it work properly..

See this question for more info

Why doesn't printf format unicode parameters?

you can use UTF-8 char set if your characters are there in this...

Printing UTF-8 strings with printf - wide vs. multibyte string literals

Community
  • 1
  • 1
smali
  • 4,687
  • 7
  • 38
  • 60