a bug in "pbcopy" using "system()" call

am losing my hair over this. when using the"pbcopy" in c++ using the system call it doesn't work with foreign languages unless its run in admin using sudo ???

system("echo привиет как дела") - works output : привиет как дела
system("echo test123 | pbcopy") - works, output to clipboard: test123
system("echo привиет как дела | pbcopy") - does not work, output to clipboard: –ø—Ä–∏–≤–∏–µ—Ç –∫–∞–∫ –¥–µ–ª–∞ 
system("echo привиет как дела | pbcopy") - using sudo to run the c++ app works, output to clipboard: привиет как дела

please help me out i don't want to use objective C NSPasteboard


Solution 1:

Essentially what happens is that when you run that echo command without sudo, your locale settings are set to the wrong language and character set (because of your environment variables) - and when you run it with sudo, this is corrected because it then evaluates the environment of the sudo'ed user so that the character is set correct (probably to UTF-8).

This is exactly similar to what happens if you used a computer with macOS set to an English locale and input settings, and then tried to run such a command (for example from a downloaded script). Because the character set is different it would work differently.

I see the same thing often here in Denmark with conflicts over ISO-8859-1 versus UTF-8 (although UTF-8 is becoming more and more ubiquitous). If the character sets do not match, the local characters (i.e. åæø ÅÆØ) becomes garbled after piping into commands such as pbcopy.

In order to avoid this, tweak your command like this when you run it in Terminal or from a program:

echo привиет как дела | LANG=en_US.UTF-8 pbcopy

Setting the character set to UTF-8 means that a very wide range of characters are supported, and it matches the character set you've probably set Terminal.app to.