snprintf(NULL,0,...);的行为是否标准化?

14

在Linux上,它返回将被打印的字符数。

这是标准化的行为吗?

2个回答

14

是的。

来自7.21.6.5 snprintf函数,N1570(C11草案):

snprintf函数类似于fprintf,不同之处在于输出写入到一个数组中(由参数s指定),而不是写入到流中。如果n为零,则不写入任何内容,s可以是空指针。否则,超出第n-1个字符的输出将被丢弃,而不是写入到数组中,并且在实际写入到数组中的字符末尾写入空字符。如果在重叠对象之间进行复制,则行为未定义。

这是一种有用的方法,可以找到未知数据的长度,您可以首先找到必要的长度,然后分配确切数量的内存。一个典型的用例是:

char *p;

int len = snprintf(0, 0, "%s %s some_long_string_here_", str1, str2);

p = malloc(len + 1);

snprintf(p, len + 1, "%s %s some_long_string_here", str1, str2);

1
好的,但你引用的是什么? - Basile Starynkevitch
C11草案,第7.21.6.5节。 - nouney

3
根据 snprintf(3),它已被 POSIX 和 C99 标准化。该手册还提到:
   Concerning the return value of snprintf(), SUSv2 and C99 contradict
   each other: when snprintf() is called with size=0 then SUSv2
   stipulates an unspecified return value less than 1, while C99 allows
   str to be NULL in this case, and gives the return value (as always)
   as the number of characters that would have been written in case the
   output string has been large enough.  POSIX.1-2001 and later align
   their specification of snprintf() with C99.

所以int i = snprintf(NULL, 0, "some-format-string",...);在失败时应该将负数放入i,在成功时应该放入非负的输出大小。

(我不确定如果输出大小大于INT_MAX会发生什么,这是非常不寻常的情况;我猜这将是一个失败的情况)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接