tags:

views:

161

answers:

1

Does anyone know why there is no snwprintf function in the C standard library?

I am aware of swprintf, but that doesn't have the same semantics of a true, wchar_t version of snprintf. As far as I can tell, there is no easy way to implement an snwprintf function using [v]swprintf:

Unlike snprintf, swprintf does not return the necessary buffer size; if the supplied buffer is insufficient, it simply returns -1. This is indistinguishable from failure due to encoding errors, so I can't keep retrying with progressively larger buffers hoping that it eventually will succeed.

I suppose I could set the last element of the buffer to be non-NUL, call swprintf, and assume that truncation occurred if that element is NUL afterward. However, is that guaranteed to work? The standard does not specify what state the buffer should be in if swprintf fails. (In contrast, snprintf describes which characters are written and which are discarded.)

+2  A: 

See the answer given by Larry Jones here.

Essentially, swprintf was added in C95 while snprintf was added in C99 and since many implementations already returned the number of required characters (for snprintf) and it seemed a useful thing to do, that was the behavior that was standardized. They didn't think that behavior was important enough to break backwards compatibility with swprintf by adding it (which was added without that behavior several years earlier).

Robert Gamble
I agree that they couldn't break backwards compatibility by changing `swprintf`, but they could have added a new `snwprintf` function.
jamesdlin
Apparently they didn't feel it would be worth it to add another function just to implement this behavior.
Robert Gamble
Actually, many historic versions of `snprintf` prior to standardization had the same broken "return -1" behavior as `swprintf`. The committee deemed it broken and specified the correct behavior instead, which broke compatibility with the old Unix (SUSv2) standard.
R..
Actually, POSIX too seems self-contradictory in this regard. It requires: "If n or more wide characters were requested to be written...set errno to indicate the error.", but `EOVERFLOW` is only documented as occurring if `n>INT_MAX` or if the resulting string would be longer than `INT_MAX`. No value of `errno` is specified for the case when the output does not fit in `n` characters...
R..