Reputation: 300
When using standard char*
strings, the snprintf
and vsnprintf
functions will return the length of the output string, even if that string was truncated due to overflow.* It seems like the ISO C committee didn't like this functionality when they added swprintf
and vswprintf
, which return -1 on overflow.
Does anyone know of a function that will provide this length? I don't know the size of the potential strings. I might be asking too much, but.. I'd rather not:
*I realize MSVC doesn't do this, and instead provides the scprintf
and vscprintf
functions, but I'm looking for other compilers, mainly GCC.
Upvotes: 1
Views: 1332
Reputation: 626
This returns the buffer size for wide character strings:
vswprintf(nullptr, -1, aFormat, argPtr);
Upvotes: 0
Reputation: 215447
My best suggestion to you would be not to use wchar_t
strings at all, especially if you're not writing Windows-oriented code. In case that's not an option, here are some other ideas:
If your format string does not contain non-ASCII characters itself, what about first calling vsnprintf
with the same set of arguments to get the length in bytes, then use that as a safe upper bound for the length in wchar_t
characters (if there are few or non-ASCII characters, the bound will be tight).
If you're okay with introducing a dependency on a POSIX function (which is likely to be added to C1x), use open_wmemstream
and fwprintf
.
Just iterate allocating larger buffers, but do it smart: increase the size geometrically at each step, e.g. 127, 255, 511, 1023, 2047, ... I like this pattern better than whole powers of 2 because it's easy to avoid dangerous case where allocation might succeed for SIZE_MAX/2+1 but then wrap to 0 at the next iteration.
Upvotes: 2