Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a wchar_t version for asprintf?

Tags:

c

printf

wchar-t

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!

like image 263
gheorghe1800 Avatar asked Jan 26 '11 20:01

gheorghe1800


2 Answers

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.

like image 129
R.. GitHub STOP HELPING ICE Avatar answered Nov 05 '22 18:11

R.. GitHub STOP HELPING ICE


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.

like image 33
Adam Rosenfield Avatar answered Nov 05 '22 17:11

Adam Rosenfield