预测sprintf()'ed line的len?

Pet*_*son 2 c printf string-length

我可以用某个函数来预测sprintf()需要的空间吗?IOW,我可以调用一个函数size_t predict_space("%s \n",some_string)来返回由sprintf("%s \n",some_string)产生的C字符串的长度吗?

pmg*_*pmg 9

C99中 snprintf (注意:Windows和SUSv2,不提供符合标准的snprintf(或_snprintf)的实现):

       7.19.6.5  The snprintf function

       Synopsis

       [#1]

               #include <stdio.h>
               int snprintf(char * restrict s, size_t n,
                       const char * restrict format, ...);

       Description

       [#2]  The snprintf function is equivalent to fprintf, except
       that the output is  written  into  an  array  (specified  by
       argument  s) rather than to a stream.  If n is zero, nothing
       is written, and s may be a null pointer.  Otherwise,  output
       characters  beyond the n-1st are discarded rather than being
       written to the array, and a null character is written at the
       end  of  the characters actually written into the array.  If
       copying  takes  place  between  objects  that  overlap,  the
       behavior is undefined.

       Returns

       [#3]  The snprintf function returns the number of characters
       that would have been written had n been sufficiently  large,
       not  counting  the terminating null character, or a negative
       value if  an  encoding  error  occurred.   Thus,  the  null-
       terminated output has been completely written if and only if
       the returned value is nonnegative and less than n.

例如:

len = snprintf(NULL, 0, "%s\n", some_string);
if (len > 0) {
    newstring = malloc(len + 1);
    if (newstring) {
        snprintf(newstring, len + 1, "%s\n", some_string);
    }
}
Run Code Online (Sandbox Code Playgroud)


Ric*_*ton 6

使用可以使用大小为0的snprintf()来确切地找出需要多少字节.价格是字符串有效格式化两次.

  • @Benoit:这不是标准描述的行为. (2认同)