我可以用某个地方来预测sprintf()需要的空间吗? IOW,我可以调用一个函数size_t predict_space(“%s \ n”,some_string)来返回由sprintf(“%s \ n”,some_string)产生的C字符串的长度吗?
答案 0 :(得分: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);
}
}
答案 1 :(得分:6)
使用可以使用大小为0的snprintf()来确切地知道需要多少字节。价格是字符串实际格式化两次。
答案 2 :(得分:2)
您可以使用snprintf
,例如
sz = snprintf (NULL, 0, fmt, arg0, arg1, ...);
但请参阅snprintf
上的Autoconf portability notes。
答案 3 :(得分:2)
在大多数情况下,您可以通过添加串联字符串的长度并根据您使用的格式获取数值的最大长度来计算它。