Question

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!

Was it helpful?

Solution

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.

OTHER TIPS

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.

Well, there seems to be a fundamental flaw in your expectations. Adding these up:

  1. Windows has what you want
  2. Linux has a non-wide variant (asprintf is not in any standard, but purely a GNU extension for Linux and *BSD).
  3. POSIX defines everything string/file related as a null-terminated char* array, which explains the lack of wide versions of pretty much any POSIX function.
  4. On top of 2, 3, and 4, all modern Linux distros are UTF-8 based, meaning that non-wide versions are what is "meant to be used".

Adding these up gives: why would you need an something like this? Surely you're not using wchar_ts on Unix are you ;). If you are, there's still two options: switch to a tchar-like solution (platform dependent typedef) or completely switch to UTF-8.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top