I need a C function which returns the final length of a formatted string so I can properly allocate the target string, rather than calculate the length myself. There is snprintf
which does just this upon inability to write the entire string, but unfortunately there is no wide char alternative for it.
swprintf
returns -1 in case of error, not the needed length (why not the same behaviour ?!?)
The title mentioned asprintf
seems to be of no help also, as it provides a non-wide version only.
_vscwprintf
can be used on windows, but I need a crossplatform, standard version, or at least a Linux version and I'll #ifdef the code.
Any ideas? Thanks!
POSIX 2008 added the open_wmemstream
function which, along with vfwprintf
, does exactly what you need. It was formerly a GNU extension, so it's been available on GNU systems for a long time.
This can easily be used to construct a awprintf
wrapper.
Yes, swprintf
. Note that despite its name, swprintf
is the wide-character equivalent of snprintf
, not sprintf
, in that it takes a buffer size as its second parameter; there is (fortunately) no wide-character version that does not take a buffer size.
Also, since it returns -1 on overflow, you'll have to get the total length of the string some other way. The only really portable way to do this is to start with a buffer of some size, try formatting and see if it's big enough, and if not, increase the size and reformat until it is big enough. This is not very efficient, as you can imagine.
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