predict len of an sprintf( )'ed line?

你说的曾经没有我的故事 提交于 2019-12-30 11:19:05

问题


Is there a function around somewhere that I can use to predict the space that sprintf( ) will need? IOW, can I call a function size_t predict_space( "%s\n", some_string ) that will return the length of the C-string that will result from sprintf( "%s\n", some_string )?


回答1:


In C99 snprintf (note: Windows and SUSv2, do not provide an implementation of snprintf (or _snprintf) conforming to the Standard):

       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.

For example:

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);
    }
}



回答2:


Use can use snprintf() with a size of of 0 to find out exactly how many bytes will be required. The price is that the string is in effect formatted twice.




回答3:


You can use snprintf for that, as in

sz = snprintf (NULL, 0, fmt, arg0, arg1, ...);

But see Autoconf's portability notes on snprintf.




回答4:


In most cases, you can compute it by adding length of the string you are concatenating and taking max length for numeric values based on the format you used.



来源:https://stackoverflow.com/questions/5338446/predict-len-of-an-sprintf-ed-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!