[英]Is there a wchar_t version for asprintf?
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. 我需要一个C函数,它返回格式化字符串的最终长度,这样我就可以正确地分配目标字符串,而不是自己计算长度。 There is
snprintf
which does just this upon inability to write the entire string, but unfortunately there is no wide char alternative for it. 有一个
snprintf
在无法写入整个字符串的情况下就这样做了,但遗憾的是没有宽字符替代它。
swprintf
returns -1 in case of error, not the needed length (why not the same behaviour ?!?) 如果出现错误,
swprintf
返回-1,而不是所需的长度(为什么不是相同的行为?!?)
The title mentioned asprintf
seems to be of no help also, as it provides a non-wide version only. 提到
asprintf
的标题似乎也没有帮助,因为它只提供非宽版本。
_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. _vscwprintf
可以在windows上使用,但我需要一个跨平台,标准版本,或至少一个Linux版本,我将#ifdef代码。
Any ideas? 有任何想法吗? Thanks!
谢谢!
Yes, swprintf
. 是的,
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; 请注意,尽管它的名称,
swprintf
是snprintf
的宽字符等价物, 而不是 sprintf
,因为它需要缓冲区大小作为其第二个参数; 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. 此外,由于它在溢出时返回-1,因此您必须以其他方式获取字符串的总长度。 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.
你可以想象这不是很有效率。
POSIX 2008 added the open_wmemstream
function which, along with vfwprintf
, does exactly what you need. POSIX 2008添加了
open_wmemstream
函数,该函数与vfwprintf
一起完全满足您的需求。 It was formerly a GNU extension, so it's been available on GNU systems for a long time. 它以前是GNU扩展,所以它已经在GNU系统上可用了很长时间。
This can easily be used to construct a awprintf
wrapper. 这可以很容易地用于构造
awprintf
包装器。
Well, there seems to be a fundamental flaw in your expectations. 好吧,你的期望似乎存在根本性的缺陷。 Adding these up:
添加这些:
asprintf
is not in any standard, but purely a GNU extension for Linux and *BSD). asprintf
不是任何标准,但纯粹是Linux和* BSD的GNU扩展)。 char*
array, which explains the lack of wide versions of pretty much any POSIX function. char*
数组,这解释了几乎没有任何POSIX函数的广泛版本的缺乏。 Adding these up gives: why would you need an something like this? 添加它们会给出:为什么你需要这样的东西? Surely you're not using
wchar_t
s on Unix are you ;)
. 当然,你不是在Unix上使用
wchar_t
s ;)
是的;)
。 If you are, there's still two options: switch to a tchar
-like solution (platform dependent typedef) or completely switch to UTF-8. 如果是,还有两个选择:切换到类似
tchar
的解决方案(平台相关的typedef)或完全切换到UTF-8。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.