Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the printf family of functions care about locale?

In iOS, if I use vswprintf with a non-western locale, it will fail and return -1.

However, if I set the locale correctly it will write properly.

Why is this? Any ideas?

like image 928
mskw Avatar asked Jul 29 '12 23:07

mskw


1 Answers

Strangely, the implementation of vswprintf on iOS converts the wide string arguments it's given to narrow strings and then converts the result back to a wide string (I had to debug this issue once). If your wide strings contain non-ASCII characters in them, then this is a lossy conversion, and only certain characters can be successfully converted.

The exact set of non-ASCII characters which can be converted depends on the current locale setting. If you try to pass in unsupported characters, then vswprintf will fail by returning -1 and setting errno to the error EILSEQ (illegal multibyte sequence).

On Mac OS X, at least, you can get around this by switching to a UTF-8 locale, e.g.:

setlocale(LC_CTYPE, "UTF-8")

However, this doesn't appear to work on iOS, so if you need to be able to vswprintf all characters without knowing the locale in advance, I'm afraid you're out of luck unless you reimplement vswprintf yourself.

like image 115
Adam Rosenfield Avatar answered Oct 12 '22 10:10

Adam Rosenfield