asprintf 有 wchar_t 版本吗?
我需要一个 C 函数来返回格式化字符串的最终长度,以便我可以正确分配目标字符串,而不是自己计算长度。有 snprintf
在无法写入整个字符串时执行此操作,但不幸的是没有宽字符替代方案。
swprintf
在出现错误时返回 -1,而不是所需的长度(为什么不具有相同的行为?!?)
提到的标题 asprintf
似乎也没有帮助,因为它仅提供非宽版本。
_vscwprintf
可以在 Windows 上使用,但我需要一个跨平台、标准版本,或者至少是一个 Linux 版本,并且我将 #ifdef 代码。
有什么想法吗?谢谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
POSIX 2008 添加了
open_wmemstream
函数,与vfwprintf
一起,完全可以满足您的需求。它以前是 GNU 扩展,因此它已经在 GNU 系统上可用很长时间了。这可以轻松地用于构造 awprintf 包装器。
POSIX 2008 added the
open_wmemstream
function which, along withvfwprintf
, 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.是的,
swprintf
。请注意,尽管名称如此,swprintf
是snprintf
的宽字符等效项,不是sprintf
,因为它将缓冲区大小作为第二个参数; (幸运的是)没有不占用缓冲区大小的宽字符版本。另外,由于它在溢出时返回 -1,因此您必须以其他方式获取字符串的总长度。唯一真正可移植的方法是从某个大小的缓冲区开始,尝试格式化并查看它是否足够大,如果不够大,则增加大小并重新格式化,直到它足够大。正如您可以想象的那样,这不是很有效。
Yes,
swprintf
. Note that despite its name,swprintf
is the wide-character equivalent ofsnprintf
, notsprintf
, 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.
嗯,你的期望似乎存在一个根本性的缺陷。将这些加起来:
asprintf
不属于任何标准,而纯粹是 Linux 和 *BSD 的 GNU 扩展)。把这些加起来就会得出:为什么你需要这样的东西?您肯定没有在 Unix 上使用
wchar_t
,是吗;)
。如果是的话,还有两个选择:切换到类似 tchar 的解决方案(依赖于平台的 typedef)或完全切换到 UTF-8。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).char*
array, which explains the lack of wide versions of pretty much any POSIX function.Adding these up gives: why would you need an something like this? Surely you're not using
wchar_t
s on Unix are you;)
. If you are, there's still two options: switch to atchar
-like solution (platform dependent typedef) or completely switch to UTF-8.