开发者

Is there a wchar_t version for asprintf?

开发者 https://www.devze.com 2023-02-06 18:09 出处:网络
I need a C function which returns the final length of a formatted s开发者_开发技巧tring so I can properly allocate the target string, rather than calculate the length myself. There is snprintf which d

I need a C function which returns the final length of a formatted s开发者_开发技巧tring 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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消