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.)
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With