¿Predecir el len de una línea sprintf () 'ed?
-
26-10-2019 - |
Pregunta
¿Existe una función en algún lugar que pueda usar para predecir el espacio que necesitará sprintf ()? Iow, ¿puedo llamar a una función size_t predicte_space ("%s n", some_string) que devolverá la longitud de la cadena C que resultará de sprintf ("%s n", some_string)?
Solución
En C99 snprintf
(Nota: Windows y SUSV2, no proporcionan una implementación de SnPrintf (o _SnPrintf) que se ajusta al estándar):
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.
Por ejemplo:
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);
}
}
Otros consejos
Use puede usar snprintf () con un tamaño de 0 para averiguar exactamente cuántos bytes se requerirán. El precio es que la cadena está en efecto formateada dos veces.
Puedes usar snprintf
para eso, como en
sz = snprintf (NULL, 0, fmt, arg0, arg1, ...);
Pero ver Autoconf's notas de portabilidad en snprintf
.
En la mayoría de los casos, puede calcularlo agregando longitud de la cadena que está concatenando y tomando la longitud máxima para valores numéricos en función del formato que utilizó.