1

I am doing an exercise where I need to write Unicode on the terminal, using only write() in <unistd.h>.

I can't use :

  • putchar
  • setlocale
  • printf (in fact the exercise is reproducing printf function)

Any "low level" advice on how to perform that?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
JSmith
  • 4,519
  • 4
  • 29
  • 45
  • 1
    Its pretty tough to read anything with the write function. As far as writing unicode to terminal is concerned, you need to know what your terminal understands. If it understands UTF-8, then you can just write that. – Chris Dodd Jan 24 '16 at 22:42
  • How printf is doing this??? – JSmith Jan 24 '16 at 22:53
  • printf just uses putchar wihich uses write. It decides what to write based on the locale. If your locale matches what the terminal understands then it just works. If not, you generally get garbage. – Chris Dodd Jan 24 '16 at 23:43

1 Answers1

4

As Chris wrote in the comments, you need a terminal (e.g. like xterm on Linux) that understands the Unicode and then you just write them. So by default xterm understands UTF8 and is set to a codepage such that this code will give you a UTF8 Smiley Face (☺).

#include <stdio.h>
#include <unistd.h>

char happy[] = { 0xe2, 0x98, 0xba };  /* U+263A */

int main()
{
   write(1, happy, 3);
   return 0;
}
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
GroovyDotCom
  • 1,304
  • 2
  • 15
  • 29
  • It would be nice to know how to convert from `0xe2 0x98 0xba` to `U+263A` and vice versa – Rugnar Oct 02 '19 at 22:03
  • see https://stackoverflow.com/questions/6240055/manually-converting-unicode-codepoints-into-utf-8-and-utf-16 or use a tool like this one: https://www.branah.com/unicode-converter – GroovyDotCom Oct 03 '19 at 19:10