mskw
mskw

Reputation: 10358

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?

Upvotes: 5

Views: 539

Answers (1)

Adam Rosenfield
Adam Rosenfield

Reputation: 400652

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.

Upvotes: 10

Related Questions