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

c – Unix to Windows:替代vsnprintf来确定长度?,第1张

概述我目前正在将我们的一个 Linux库的代码转换为Windows DLL. 在这个库中,我有一个函数,它以printf-way(格式字符串, 那么省略号).在这个函数中,我使用vsnprintf格式化提供的参数. 因为我想知道我是否可以将最终的字符串填充到一个小的缓冲区,或者我必须分配 内存为它,我有兴趣确定格式化字符串的“长度”. 为了做到这一点,我目前正在使用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上提供此功能,所以依靠“未指定的行为”是不必要的.

总结

以上是内存溢出为你收集整理的c – Unix to Windows:替代vsnprintf来确定长度?全部内容,希望文章能够帮你解决c – Unix to Windows:替代vsnprintf来确定长度?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1248623.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-07
下一篇 2022-06-07

发表评论

登录后才能评论

评论列表(0条)

保存