问题
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:
- allocate a huge static temp buffer
- iteratively allocate and free memory until i've found a size that fits
- add an additional library dependency
- write my own format string parser
*I realize MSVC doesn't do this, and instead provides the scprintf
and vscprintf
functions, but I'm looking for other compilers, mainly GCC.
回答1:
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 inwchar_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
andfwprintf
.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.
回答2:
This returns the buffer size for wide character strings:
vswprintf(nullptr, -1, aFormat, argPtr);
来源:https://stackoverflow.com/questions/6132009/getting-the-length-of-a-formatted-string-from-wsprintf