Is there a wchar_t version for asprintf?

I need a C function that returns the final length of a formatted string so that I can correctly select the target string and not calculate the length myself. There is snprintf that does this only when it is not possible to write the entire string, but unfortunately there is no wide alternative to char for it.

swprintf returns -1 in case of an error, and not the required length (why not the same behavior?!?)

The name mentioned by asprintf also does not help, as it provides only a narrow version.

_vscwprintf can be used on Windows, but I need a cross-platform, standard version, or at least a version for Linux, and I will #ifdef the code.

Any ideas? Thanks!

+7
source share
3 answers

POSIX 2008 added the open_wmemstream function, which, together with vfwprintf does exactly what you need. This was previously a GNU extension, so it has been available on GNU systems for a long time.

This can easily be used to create awprintf wrappers.

+3
source

Yes, swprintf . Note that despite its name, swprintf is the wide-character equivalent of snprintf , not sprintf , as it takes the size of the buffer as the second parameter; (fortunately) there is no widescreen version that does not accept the size of the buffer.

Also, since it returns -1 on overflow, you have to get the total length of the string in another way. The only really portable way to do this is to start with a buffer of some size, try formatting and see if it is enough, and if not, increase the size and reformat it until it gets big enough. It is not very effective as you can imagine.

+3
source

Well, it looks like there is a fundamental flaw in your expectations. Add them up:

  • Windows has what you want.
  • Linux has a narrow version ( asprintf not included in any standard, but is simply an extension of GNU for Linux and * BSD).
  • POSIX defines all lines / files associated with a zero-terminated char* array, which explains the lack of wide versions of almost any POSIX function.
  • In addition to 2, 3, and 4, all modern Linux distributions are based on UTF-8, which means that the smaller versions are what are โ€œintended for useโ€.

Adding these sentences gives: why do you need something like this? Don't you use wchar_t on Unix, you ;) . If so, there are still two options: switch to a tchar solution (depending on the typedef platform) or switch completely to UTF-8.

+2
source

All Articles