Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

wprintf UTF16 (should be UTF8) on Linux?

  1. It's really strange that wprintf shows 'Ω' as 3A9 (UTF16), but wctomb converts wchar to CEA9 (UTF8); my locale is the default en_US.utf8. As man-pages said, they should conform to my locale, but wprintf uses UTF16 - why?

    Excerpt from http://www.fileformat.info/info/unicode/char/3a9/index.htm:

    Ω in UTF

    UTF-8 (hex) 0xCE 0xA9 (cea9)

    UTF-16 (hex) 0x03A9 (03a9)

  2. wprintf and printf just cannot be run in the same program, I have to choose to use either wprintf or printf. Why?


My program looks like this:

#include <stdio.h>
#include <wchar.h>
#include <stdlib.h>
#include <locale.h>
 
int main() {
  setlocale(LC_ALL,""); // inherit locale setting from environment
  int r;
  char wc_char[4] = {0,0,0,0};
  wchar_t myChar1 = L'Ω'; //greek 
  
  // should comment out either wprintf or printf, they don't run together
  r = wprintf(L"char is %lc (%x)\n", myChar1, myChar1);//On Linux, to UTF16
   
  r = wctomb(wc_char, myChar1); // On Linux, to UTF8
  r = printf("r:%d, %x, %x, %x, %x\n", r, wc_char[0], wc_char[1], wc_char[2], wc_char[3]);
}
like image 808
davy Avatar asked Aug 19 '26 17:08

davy


1 Answers

The answer to your second question has to do with stream orientation. You cannot mix printf() and wprintf() because they require different orientations.

When the process starts, the streams are not set yet. On the first call to a function that uses the stream, it gets set accordingly. printf() will set the orientation to normal, and wprintf() will set it to wide.

It is undefined behavior to call a function that requires a different orientation as the current setting.

like image 183
Mysticial Avatar answered Aug 22 '26 07:08

Mysticial



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!