微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c – Unix to Windows:替代vsnprintf来确定长度?

我目前正在将我们的一个 Linux库的代码转换为Windows DLL.

在这个库中,我有一个函数,它以printf-way(格式字符串,
那么省略号).在这函数中,我使用vsnprintf格式化提供的参数.
因为我想知道我是否可以将最终的字符串填充到一个小的缓冲区,或者我必须分配
内存为它,我有兴趣确定格式化字符串的“长度”.

为了做到这一点,我目前正在使用vsnprintf(显而易见的是编写示例代码):

#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>

void foo(const char* fmt,...)
{
   int len = 0;
   va_list ap;

   va_start(ap,fmt);
   len = vsnprintf(0,fmt,ap);
   printf("len = %d\n",len);
   va_end(ap);
}

int main(void)
{
   foo("12345%s","67890");
   exit(0);
}

Open Group Base Specifications Issue 6的这个用法涵盖:

vsnprintf(char *restrict s,size_t n,const char *restrict format,va_list ap)

The […] vsnprintf() […] functions shall be equivalent to […] snprintf().

snprintf(char *restrict s,…)

If the value of n is zero on a call to snprintf(),nothing shall be written,the number of bytes that would have been written had n been sufficiently large excluding the terminating null shall be returned,and s may be a null pointer.

当我在Windows系统(Visual Studio 2010)上使用/ analyze进行编译时,出现了问题.编译器/分析仪给了我以下内容

test.c(11) : warning C6309: Argument ‘1’ is null: this does not adhere to function specification of ‘vsnprintf’

test.c(11) : warning C6387: ‘argument 1’ might be ‘0’: this does not adhere to the specification for the function ‘vsnprintf’: Lines: 7,8,10,11

快速浏览MSDN entry for vsnprintf给了我这个:

If buffer or format is NULL,or if count is less than or equal to zero,these functions invoke the invalid parameter handler,as described in Parameter Validation. If execution is allowed to continue,these functions return -1.

好奇的是,上述示例在Windows上“按预期”(即返回给我写入的字符数).

但是,由于我不希望这些依赖于一些不明确的东西,我想知道如果有更好的官方方式实现同​​样的目标,而不必希望在将来的某个版本中不会有任何冲突.

谢谢你的时间!

解决方法

Hans Passant评论中提供的答案:

记录的_vscprintf在Windows上提供此功能,所以依靠“未指定的行为”是不必要的.

原文地址:https://www.jb51.cc/c/114249.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐